<?php

namespace App\Http\Controllers\Api\V4;

use App\Common\ApiData;
use App\Common\Jpush;
use App\Events\NoticeUserEvent;
use App\Models\V2\BookModel;
use App\Models\V2\CommentReply;
use App\Models\V2\CompanyModel;
use App\Models\V2\MemberModel;
use App\Models\V2\MessageModel;
use App\Models\V2\NoticeUser;
use App\Models\V2\ReadPartyModel;

use App\Repository\Comment;
use Carbon\Carbon;
use Dingo\Api\Routing\Helpers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Validator;

use App\Modules\EntMemberInfo;
use App\Modules\EntReadingParty;

use App\Modules\EntCommZanLog;
use App\Modules\EntCommentReply;


class ReadingPartyController extends Controller
{
    use Helpers, Comment;
    protected $url;
    protected $urlapi;
    protected $fileTypes = ['jpg', 'jpeg', 'png'];
    protected $isReaParID = 0;

    public function __construct()
    {
        $this->middleware(['checkUserSign'], ['only' => 'reward']);
        $this->url    = env('ADMIN_HOST');
        $this->urlapi = env('API_HOST');
    }

    //======================================v2 begin=========================

    /*========= 1.读书会首页  读书详情页 =============*/

    /**
     * 改进计划分页
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function paginate_book_sumup(Request $request)
    {
        $apiData      = new ApiData();
        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $parid        = $request->input('parid');
        $bookId       = $request->input('id');
        $page         = $request->input('page');
        $departmentId = $request->input('departmentId', -1);
        $params       = [
            'mobile' => [$mobile, '缺少手机号', '2037'],
            'key'    => [$key, "缺少设备ID", '2038'],
            'bookId' => [$bookId, '缺少书籍ID', '6001'],
            'parid'  => [$parid, "缺少读书会ID", '6005'],
            'page'   => [$page, "缺少页数", '6002']
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }
        $bookModel      = new BookModel();
        $bookSumup      = $bookModel->get_read_plan_by_book_readparty($bookId, $parid, $departmentId);
        $readPartyModel = new ReadPartyModel();
        foreach ($bookSumup as $data) {
            $readPartyId = $parid;
            $commentId   = $data->SumUpID;
            //取出该评论的打赏记录
            $zanList   = $readPartyModel->get_read_plan_money_gift($commentId, $readPartyId);
            $data->zan = $zanList;
            //评论
            $commentreply      = $readPartyModel->get_read_plan_comment($commentId, $readPartyId);
            $data->commentlist = $commentreply;
        }
        $apiData->message = "ok";
        $apiData->code    = "200";
        $apiData->set_data('readPlanList', $bookSumup);
        return $apiData->send_old();
    }





    /*========= 2. 创建个人、企业读书会 =============*/


    /**
     * 创建个人读书会 类型:2
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_personal_read_party(Request $request)
    {
        $request->offsetSet('readPartyType', 2);
        $apiData = $this->add_read_party($request);
        return $apiData->send();
    }


    /**
     * 添加公司读书会 type:1
     * */
    public function add_company_read_party_v3(Request $request)
    {
        $request->offsetSet('readPartyType', 1);
        $apiData = $this->add_read_party($request);
        return $apiData->send();
    }


    /**
     * 创建读书会
     * */
    public function add_read_party(Request $request)
    {
        define('_qiye_', 1);
        define('_geren_', 2);

        $apiData     = new ApiData();
        $readModel   = new ReadPartyModel();
        $memberModel = new MemberModel();

        $mobile = $request->input('mobile');
        $appKey = $request->input('key');
        $readPartyName = $request->input('reaparname');
        $regulation    = $request->input('regulation');
        $readPartyType = $request->input('readPartyType');

        $memberInfo = $memberModel->get_member_info_by_mobile_key($mobile, $appKey);
        $userId     = $memberInfo->UserID;
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3005";
            return $apiData;
        }

        //0.检查参数
        $paras  = [
            //'readPartyName' => [$readPartyName, '读书会名称不能为空', '10001'],
            'regulation'    => [$regulation, '读书会规则不能为空', '1002']
        ];
        $result = $this->check_params($paras);
        if ($result->code != '200') {
            $apiData->code    = $result->code;
            $apiData->message = $result->message;
            return $apiData;
        }

        //1.检查读书会是否被创建
        if($readPartyType == _geren_ && $readModel->check_read_party_name_exists($readPartyName) == true) {
            $apiData->code    = "2001";
            $apiData->message = "读书会名称已被使用";
            return $apiData;
        }

        //1：企业读书会 2：个人读书会

        //2.如果创建的是企业读书会
        if ($readPartyType == _qiye_) {
            $companyModel = new CompanyModel();
            //2.1判断公司情况
            $companySn      = trim($request->input('companySn'));
            $companyInfo    = $companyModel->get_company_info_by_sn($companySn);
            if ($companyInfo == false) {
                $apiData->message = "公司不存在";
                $apiData->code    = "5002";
                return $apiData;
            }
            $companyId = $companyInfo->company_id;
	    $readPartyName = $companyInfo->company_name;

            //检查本公司是否已经有了读书会
            $companyReadPartys = $companyModel->get_company_read_partys($companyId);
            if (count($companyReadPartys) > 0) {
                $apiData->code    = "5003";
                $apiData->message = "该公司编号已被使用";
                return $apiData;
            }
        } else {
            $companyId = 0;
        }

        $companyname   = $request->input('companyname');
        $tel           = $request->input('tel');
        $createrName   = $request->input('creatername');
        $readPartyData = [
            'States'      => 1,
            'Tel'         => $tel,
            'ReaParType'  => $readPartyType,
            'Regulation'  => $regulation,
            'ReaParName'  => $readPartyName,
            'MemNumber'   => $memberInfo->MemNumber,
            'company_id'  => $companyId,
            'companyname' => $companyname,
            'CreaterName' => $createrName,
        ];

        $readPartyId = $readModel->add_read_party($readPartyData);
        //添加一个未分组部门
        if($readPartyType == _qiye_)
        {
            $department = [
                'department_name'   => '未分组',
                'company_id'        => $companyId,
                'read_party_id'     => $readPartyId
            ];
            $departmentId = DB::table('company_department')->insertGetId($department);
        }
        else
        {
            $departmentId   = 0;
        }

        //将创建者拉入读书会  如果是应该有一个部门
        $otherData   = [
            'look_gift_right'   => 1,
            'reward_right'      => 1
        ];
        $result = $readModel->add_read_party_member($readPartyId, $userId,$departmentId,$otherData);

        if ($readPartyType == _qiye_)
        {
            //检查用户是否已存在该公司 如果不是 加入该公司 扣除端口
            if ($companyModel->company_exists_member($companyId, $userId) == false) {
                $companyModel->add_company_member($companyId, $departmentId, $userId);
                $companyModel->use_company_port($companyId, 1);
            }
            $data       = [
                'UserID'     => $memberInfo->UserID,
                'States'     => 1,
            ];
            $memberModel->update_member_info($data);
            $memberModel->change_member_endtime($userId);
        }

        if ($result != true) {
            $apiData->code    = "403";
            $apiData->message = "读书会添加失败";
        }

        //3.保存图片
        $imgName      = $request->input('imgName');
        $readPartyImg = $request->file('readPartyImg');
        $msg          = "";
        if ($imgName) {
            $filetype = explode('.', $imgName);
            if (!isset($filetype[1]) || !in_array($filetype[1], $this->fileTypes)) {
                $msg = "图片类型未知或图片格式不在允许范围内";
            } else {
                //文件上传路径
                $facepath = 'groupface';
                $fileName = "1-" . $readPartyId . '.' . $filetype[1];

                $file = Storage::putFileAs($facepath, $readPartyImg, $fileName);
                if ($file == '') {
                    $msg = "图片保存失败";
                } else {

                    $data = ['FilePath1' => "/uploads/" . $file];
                    $readModel->update_read_party($readPartyId, $data);
                }
            }
        }

        $apiData->set_data('readPartyId', $readPartyId);
        $apiData->code    = '200';
        $apiData->message = '读书会添加成功,' . $msg;
        return $apiData;
    }



    /*========== 3.管理读书会 =================*/
    /**
     * 删除读书会
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function readingPartyDelete(Request $request)
    {
        $result    = 'no';
        $rules     = [
            'id'        => 'required',
            'mobile'    => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages  = [
            'id.required'        => '2039',
            'mobile.required'    => '2037',
            'key.required'       => '2038',
            'timestamp.required' => '2040',
            'sign.required'      => '2041'
        ];
        $id        = $request->input('id');
        $mobile    = $request->input('mobile');
        $key       = $request->input('key');
        $sign      = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params    = ['mobile' => $mobile, 'key' => $key, 'id' => $id, 'timestamp' => $timestamp, 'sign' => $sign];
        $v         = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        if ($this->checkSign($params) == true) {
            $member = $this->memNumber($mobile, $key);
            if ($member) {
                $entReadingParty = EntReadingParty::find($id);
                if ($member->MemNumber == $entReadingParty->MemNumber) {
                    EntReadingParty::where('ReaParID', $entReadingParty->ReaParID)->update(['DeleteMark' => '0']);
                    return response()->json(['message' => 'ok', 'code' => '200']);
                } else {
                    //权限不足
                    return response()->json(['message' => $result, 'code' => '3069']);
                }
            } else {
                return response()->json(['message' => $result, 'code' => '3027']);
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3028']);
        }
    }


    /**
     * 修改读书会头像 1--小图 2--大图
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_read_party_img(Request $request)
    {
        $id     = $request->input('id');
        $type   = $request->input('type');
        $name   = $request->input('name');
        $mobile = $request->input('mobile');
        $key    = $request->input('key');

        $params = [
            'id'     => [$id, '缺少读书会ID', '2098'],
            'mobile' => [$mobile, '缺少手机号', '2073'],
            'key'    => [$key, '缺少key', '2070'],
            'name'   => [$name, '缺少图片名称', '2069'],
            'type'   => [$type, '不知道是小图还是大图', '2099'],
        ];

        $apiData = new ApiData();

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3052";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($id);
        if($readPartyInfo == false) { //读书会信息读取失败
            $apiData->message = "读书会不存在";
            $apiData->code    = "3076";
            return $apiData->send();
        }

        $isClo          = $this->isDrp($memberInfo->UserID,$readPartyInfo->company_id);

        if ($memberInfo->MemNumber != $readPartyInfo->MemNumber && !$isClo) { //没有修改头像的权限
            $apiData->message = "权限不足";
            $apiData->code    = "3077";
            return $apiData->send();
        }


        $filetype = explode('.', $name);

        if (!isset($filetype[1]) || !in_array($filetype[1], $this->fileTypes)) {
            $apiData->message = "图片类型未知或图片格式不在允许范围内";
            $apiData->code    = "3053";
            return $apiData->send();
        }
        //文件上传路径
        $facepath = 'groupface';
        $fileName = $type . "-" . $id . '-' . time() . '.' . $filetype[1];
        $file     = Storage::putFileAs($facepath, $request->file('img'), $fileName);
        if ($file == '') {
            $apiData->message = "图片保存失败";
            $apiData->code    = "3055";
            return $apiData->send();
        }

        $memfacceurl = '/uploads/' . $file;
        $fileColum   = "FilePath" . $type;
        $readData    = [$fileColum => $memfacceurl];
        $readPartyModel->update_read_party($id, $readData);

        $apiData->message = "保存成功";
        $apiData->code    = "200";
        $apiData->set_data('file', env('ADMIN_HOST') . $memfacceurl);
        return $apiData->send_old();
    }


    /**
     * 管理员修改群规
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_read_party_gulation(Request $request)
    {
        $request->offsetSet('readPartyId', $request->input('id'));
        return $this->update_read_party_info($request);
    }


    /*
     * 修改读书会信息
     * */
    public function update_read_party_info(Request $request)
    {
        $apiData = new ApiData();


        $readPartyId = $request->input('readPartyId');
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');

        $params = [
            'mobile' => [$mobile, "手机号为空", "2082"],
            'key'    => [$key, "设备ID为空", "2083"],
            'id'     => [$readPartyId, "读书会ID为空", "2093"],
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3056";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        if ($readPartyInfo == false) {
            $apiData->message = "读书会不存在";
            $apiData->code    = "3069";
            return $apiData->send();
        }

        $isClo          = $this->isDrp($memberInfo->UserID,$readPartyInfo->company_id);
        if ($memberInfo->MemNumber != $readPartyInfo->MemNumber && !$isClo)
        {
            $apiData->message = "权限不足";
            $apiData->code    = "3069";
            return $apiData->send();
        }

        //修改名称

        $newReadPartyInfo = [
            'Regulation'  => $request->input('regulation'),
            'CompanyName' => $request->input('companyName'),
            'Tel'         => $request->input('tel'),
            'ReaParName'  => $request->input('readPartyName'),
            'createrName' => $request->input('createrName'),
        ];
        $newReadPartyInfo = array_filter($newReadPartyInfo);

        $result = $readPartyModel->update_read_party($readPartyId, $newReadPartyInfo);
        if ($result) {
            $apiData->message = "读书会信息修改成功";
            $apiData->code    = "200";
        } else {
            $apiData->message = "读书会修改失败";
            $apiData->code    = "3059";
        }
        return $apiData->send();

    }

    /*========== 4.读书会会员管理 ===========


    =====*/

    /**
     * 会员通讯录中哪些用户可以添加为会员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function check_member_mobile_list(Request $request)
    {
        $beginTime = time();

        $data = '[{"name":"张维喜","mobileList":["150006069424","x13540381839"]},{"name":"王五","mobileList":["18604074775","xxx","xxx"]}]';

        $readPartyId = $request->input('id');        //读书会ID
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');
        $moblist     = $request->input('userList');
        $userList    = json_decode(urldecode($moblist));


        $params = [
            'mobile'  => [$mobile, "手机号为空", "2037"],
            'key'     => [$key, "设备ID异常", "2038"],
            'id'      => [$readPartyId, "读书会ID异常", "2039"],
            'moblist' => [$userList, "会员列表异常", "6002"]
        ];

        $apiData = new ApiData();
        $apiData->set_data('memberlist', []);

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->code    = $checkResult->code;
            $apiData->message = $checkResult->message;

            return $apiData->send();
        }


        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);


        if ($memberInfo == false) {
            $apiData->message = "用户验证失败";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);

        //1.检查权限
        if ($readPartyInfo->MemNumber != $memberInfo->MemNumber) {
            $apiData->message = "只有管理员才能添加会员";
            $apiData->code    = "3078";
            return $apiData->send();
        }

        //遍历用户
        $users = [];
        foreach ($userList as $key => $user) {

            $userInfo = [
                'isVip'      => 0,   //是否是会员  0:不是 1:是
                'needInvite' => 0,   //是否需要邀请 0:不邀请 1：邀请
                'headImg'    => "",
                'memNumber'  => "",
                'yourName'   => $user->name
            ];

            $inviterMobiles = $user->mobileList;    //一个用户可能有多个手机号码 所以对手机号码进行逐个判断
            foreach ($inviterMobiles as $inviterMobile) {
                //获取被邀请者信息
                $inviterInfo = $memberModel->get_member_info_by_mobile($inviterMobile);
                if ($inviterInfo == false || $inviterInfo->States != '1') {
                    continue;
                }

                $userInfo['isVip']     = 1;    //用户存在
                $userInfo['memNumber'] = $inviterInfo->MemNumber;
                $userInfo['headImg']   = $inviterInfo->headImg;

                //检查用户是否加入了读书会
                $isJoinRead = $readPartyModel->check_read_party_member_exists($readPartyId, $inviterInfo->UserID);
                if ($isJoinRead == true) {

                    break;
                } else {
                    $userInfo['needInvite'] = 1; //用户未加入读书会，可以邀请
                }
            }
            if ($userInfo['isVip'] == 1) {
                array_push($users, $userInfo);
            }
        }
        $endTime = time();

        $apiData->message = "ok";
        $apiData->code    = "200";
        $apiData->set_data('memberlist', $users);
        return $apiData->send_old();
    }


    /**
     * 添加读书会成员   从通讯录中添加
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_read_party_member(Request $request)
    {
        define('_qiye_', 1);
        define('_geren_', 2);

        $apiData = new ApiData();

        $readId = $request->input('id');
        $mobile = $request->input('mobile');
        $key    = $request->input('key');
        $memid  = $request->input('memid');

        $userMobile   = $request->input('userMobile');
        $userName     = $request->input('userName');
        $job          = $request->input('job');
        $rewardRight  = $request->input('rewardRight') == 1 ? true : false;
        $departmentId = $request->input('departmentId',0);

        $data = [
            'id'     => [$readId, "缺少读书会ID", '2039'],
            'mobile' => [$mobile, "缺少手机号", '2037'],
            'key'    => [$key, "缺少设备ID", "2038"]
        ];

        $result = $this->check_params($data);
        if ($result->code != '200') {
            $apiData->message = $result->message;
            $apiData->code    = $result->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();

        //1.检查登录者
        $managerInfo = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($managerInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();

        //2.检查读书会
        $readPartyInfo = $readPartyModel->get_read_party_info($readId);
        if (!$readPartyInfo) { //读书会信息读取失败
            $apiData->message = "读书会不存在";
            $apiData->code    = "3065";
            return $apiData->send();
        }


        //3.检查是否是管理员
        if ($managerInfo->MemNumber != $readPartyInfo->MemNumber) { //权限不足

            //3.1判断是不是学习官
            $isReadpartyClo = DB::table('read_party_member')
                ->where('read_party_id',$readId)
                ->where('user_id',$managerInfo->UserID)
                ->where('is_delete',0)
                ->first();
            if(!$isReadpartyClo)
            {
                $apiData->message = "权限不足";
                $apiData->code    = "3066";
                return $apiData->send();
            }
        }

        //4.检查该读书会是个人读书会还是企业读书会  企业读书会是需要限制端口数量的  1:企业 2.个人
        if ($readPartyInfo->ReaParType == _qiye_) {

            if (!preg_match('/^\d{6,20}$/', $userMobile)) {
                return $apiData->send("3021", "手机号格式错误");
            }

            //获取企业信息
            $companyModel = new CompanyModel();
            $companyInfo  = $companyModel->get_company_info($readPartyInfo->company_id);
            $companyId    = $companyInfo->company_id;
            $beginTime    = strtotime($companyInfo->vip_begin_date);
            $endTime      = strtotime($companyInfo->vip_end_date);
            $time         = time();


            //4.2检查企业的有效期
            if ($beginTime > $time || $endTime < $time) {
                $apiData->code    = "3066";
                $apiData->message = "企业的有效服务期已失效";
                return $apiData->send();
            }
        }

        //6.检查被添加的会员是否存在

        if ($readPartyInfo->ReaParType == _geren_) {

            //6.1判断被添加用户是否存在
            $invitedMember = $memberModel->get_member_info_by_member_number($memid);
            if ($invitedMember == false) {
                $apiData->message = "被邀请的会员不存在";
                $apiData->code    = "3067";
                return $apiData->send();
            }
        } elseif ($readPartyInfo->ReaParType == _qiye_) {
            $invitedMember = $memberModel->get_member_info_by_mobile($userMobile);
        }


        //检查该用户是否加入了读书会
        if ($invitedMember) {
            $isExists = $readPartyModel->check_read_party_member_exists($readId, $invitedMember->UserID);
            if ($isExists == true) {
                $apiData->message = "该用户已是读书会会员";
                $apiData->code    = "3102";
                return $apiData->send();
            }
        }


        if ($readPartyInfo->ReaParType == _qiye_) {
            //如果系统不存在员工或则员工不存在公司里边
            $needCheck = false;
            if ($invitedMember == false) {
                $needCheck = true;
            } elseif (!$companyModel->company_exists_member($companyId, $invitedMember->UserID)) {
                $needCheck = true;
            }

            //4.3检查企业的端口数量
            $readPartyTotalNumber   = $readPartyModel->count_read_party_number($readId);
            //if ($needCheck && $readPartyTotalNumber >= $companyInfo->vip_port) {
            if ($readPartyTotalNumber >= $companyInfo->vip_port) {
                return $apiData->send("3066", "端口不足");
            }

            //新添加的会员的时间 = 个人时间 + 公司时间
            if ($invitedMember == false) {
                $userInfo = [
                    "MemNumber"    => create_member_number(),
                    "UserName"     => $userMobile,
                    "NickName"     => $userName,
                    "YourName"     => $userName,
                    "RegisterType" => "企业加入",
                    'AppKey'       => "",
                    "wx_unionid"   => "",
                    'app_openid'   => "",
                    'head_img'     => "",
                    'sex'          => "n",
                ];
                $memberModel->register($userInfo);
                $invitedMember = $memberModel->get_member_info_by_mobile($userMobile);
            }

            //检查用户是否加入该公司 设置会员的部门ID 修改会员的有效时间

            $userId = $invitedMember->UserID;

            if ($companyModel->company_exists_member($companyId, $userId)) {
                //已存在 则修改
                $companyModel->update_company_member($userId, $companyId, ['department_id' => $departmentId, 'job' => $job]);
            } else {
                //不存在  则添加 并扣除端口
                $companyModel->add_company_member($companyId, $departmentId, $userId, $job);
                $companyModel->use_company_port($companyId, 1);
            }
            $updateInfo  = [
                "States"     => 1,               //会员状态
                'UserID'     => $userId
            ];

            $memberModel->update_member_info($updateInfo);
            $memberModel->change_member_endtime($userId);
        }

        try {
            $readPartyModel->add_read_party_member($readId,$invitedMember->UserID,$departmentId,['reward_right'=>$rewardRight]);
            //发送消息推送
            $msg      = "读书会会长" . $managerInfo->YourName . "邀请您加入" . $readPartyInfo->ReaParName . "读书会";
            $msgModel = new MessageModel();
            $msgId    = $msgModel->add_note_message('读书会邀请', $msg);
            $msgModel->add_user_message($msgId, $invitedMember->UserID);
            //1.极光推送--增加读书会的ID，ReadParType读书会的类型 code为int 204 时间读书创建的时间
            $ReadParType = $readPartyInfo->ReaParType;//1为企业 2为个人
            $message     = ['ReadParId' => $readId, 'type' => $ReadParType];
            $data        = ['code' => 204, 'message' => json_encode($message)];
            $this->JpushContent($msg, $invitedMember->UserName, '读书会邀请', $data);
        } catch (Exception $e) {
            return $apiData->send("3067", "加入失败");
        }
        return $apiData->send('200', 'ok');
    }


    /**
     * 读书俱乐部的所有成员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function read_party_all_member(Request $request)
    {
        $apiData     = new ApiData();
        $readPartyId = $request->input('id');
        $page        = $request->input('page');
        $keyword     = $request->input('keyword');
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');
        $depatmentId = $request->input('departmentId', -1);
        $depatmentId = $depatmentId === '' ? -1 : $depatmentId;

        $params = [
            'mobile' => [$mobile, "缺少手机号", "2037"],
            'key'    => [$key, "缺少设备ID", "2038"],
            'id'     => [$readPartyId, "缺少读书会ID", "2039"]
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }


        //读书会信息
        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        if (!$readPartyInfo) {
            $apiData->message = "读书会不存在";
            $apiData->code    = "402";
            return $apiData->send();
        }

        $groupid   = $readPartyInfo->ReaParID;
        $groupname = $readPartyInfo->ReaParName;
        $addDate   = $readPartyInfo->AddDate;
        $rule      = $readPartyInfo->Regulation;

        if ($depatmentId >= 0) {
            $readPartyMembers = $readPartyModel->get_read_party_department_member($readPartyId, $depatmentId);
        } else {

            $readPartyMembers = $readPartyModel->get_read_party_member($readPartyId, $keyword, 1000);
        }


        //是否是群主 0--不是 1--是
        $isadmin = 0;
        if ($readPartyInfo->MemNumber == $memberInfo->MemNumber) {
            $isadmin = 1;
        }

        foreach ($readPartyMembers as $v) {
            if ($v->MemNumber == $readPartyInfo->MemNumber) {
                $v->isAdmin = 1;
            } else {
                $v->isAdmin = 0;
            }
            $v->StudyMoney = $v->StudyMoney ? $v->StudyMoney : 0;
        }

        $apiData->message = "ok";
        $apiData->code    = "200";
        $apiData->set_data('groupid', $groupid)
            ->set_data('groupname', $groupname)
            ->set_data('rule', $rule)
            ->set_data('time', $addDate)
            ->set_data('isadmin', $isadmin)
            ->set_data('memberlist', $readPartyMembers);
        return $apiData->send_old();
    }

    /**
     * 读书会部门成员
     * */
    public function read_party_department_member(Request $request)
    {
        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $readPartyId  = $request->input('readPartyId');
        $departmentId = $request->input('departmentId');
        $apiData      = new ApiData();

        $readPartyModel   = new ReadPartyModel();
        $members          = $readPartyModel->get_read_party_department_member($readPartyId, $departmentId);
        $apiData->message = "获取成功";
        $apiData->code    = "200";
        $apiData->set_data('members', $members);
        return $apiData->send();
    }


    /**
     * 读书会会员详细信息
     *
     * */
    public function read_party_member_detail(Request $request)
    {
        $readPartyId = $request->input('readPartyId');
        $userId      = $request->input('userId');
        $apiData     = new ApiData();
        $memberModel = new MemberModel();
        $userInfo    = $memberModel->get_member_info_by_id($userId);
        if (!$userInfo) {
            $apiData->message = "用户不存在";
            $apiData->code    = "2002";
            return $apiData->send();
        }
        unset($userInfo->LoginKey);
        unset($userInfo->AppKey);


        $readPartyModel        = new ReadPartyModel();
        $bookModel             = new BookModel();
        $readPartyMemberDetail = $readPartyModel->get_read_party_member_detail($userInfo->UserID, $readPartyId);
        if ($readPartyMemberDetail == false) {
            $apiData->message = "用户已被移出读书会";
            $apiData->code    = "2002";
            return $apiData->send();
        }
        $companyModel      = new CompanyModel();
        $readPartyInfo     = $readPartyModel->get_read_party_info($readPartyId);
        $companyId         = $readPartyInfo->company_id;
        $memberCompanyInfo = $companyModel->get_company_member_info($companyId, $userId);

        $departmentId = $memberCompanyInfo->department_id;

        if ($departmentId > 0) {
            $userInfo->department_name = $memberCompanyInfo->department_name;
            $userInfo->department_id   = $departmentId;
        } else {
            $userInfo->department_name = "未分组";
            $userInfo->department_id   = 0;
        }
        $userInfo->job              = $memberCompanyInfo->job;
        $readedBook                 = $bookModel->get_user_readed_book($userInfo->MemNumber);
        $userInfo->isEmployee       = $readPartyMemberDetail->is_delete === 1 ? 0 : 1;
        $userInfo->rewardRight      = $readPartyMemberDetail->reward_right;
        $userInfo->readedBookNumber = count($readedBook);
        $apiData->message           = "ok";
        $apiData->code              = "200";
        $apiData->set_data('memberInfo', $userInfo);

        return $apiData->send();
    }

    /**
     * 退出读书会
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function quit_read_party(Request $request)
    {
        $apiData     = new ApiData();
        $readPartyId = $request->input('id');
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');

        $params      = [
            'mobile'      => [$mobile, "缺少手机号", "2037"],
            'key'         => [$key, "缺少设备ID", "2038"],
            'readPartyid' => [$readPartyId, "缺少读书会ID", "2039"]
        ];
        $paramsCheck = $this->check_params($params);
        if ($paramsCheck->status == false) {
            $apiData->message = $paramsCheck->message;
            $apiData->code    = $paramsCheck->code;
            return $apiData->send();
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $result         = $readPartyModel->remove_party_member($readPartyId, $memberInfo->UserID);
        if ($result) {
            $apiData->message = "退出读书会成功";
            $apiData->code    = "200";
        } else {
            $apiData->message = "退出读书会失败";
            $apiData->code    = "3027";
        }
        return $apiData->send();
    }


    /**
     * 管理员删除读书会成员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function manager_remove_read_party_member(Request $request)
    {
        mylogger('zhangweixi');
        mylogger($request->all());
        $apiData     = new ApiData();
        $readPartyId = $request->input('id');
        $memid       = $request->input('memid');
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');
        $sign        = $request->input('sign');
        $timestamp   = $request->input('timestamp');

        $params = [
            'mobile' => [$mobile, "缺少手机号", "2037"],
            'key'    => [$key, "缺少设备ID", "0238"],
            'id'     => [$readPartyId, "缺少读书会ID", "2039"],
            'memid'  => [$memid, "缺少会员ID", '2110'],
            //'timestamp' => [$timestamp,"缺少时间戳","2040"],
            //'sign'      => [$sign,"缺少签名","2041"]
        ];

        $paCheckResult = $this->check_params($params);
        if ($paCheckResult->status == false) {
            $apiData->message = $paCheckResult->message;
            $apiData->code    = $paCheckResult->code;
            return $apiData->send();
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        if ($readPartyInfo->MemNumber != $memberInfo->MemNumber) {
            $apiData->message = "权限不足";
            $apiData->code    = "3013";
            return $apiData->send();
        }

        $readPartyMemberInfo = $memberModel->get_member_info_by_member_number($memid);
        $userId              = $readPartyMemberInfo->UserID;
        $result              = $readPartyModel->remove_party_member($readPartyId, $userId);
        if ($result) {
            $apiData->message = "删除成功";
            $apiData->code    = "200";
            //EntReaParLog::where('MemNumber', $memid)->where('ReaParID', $id)->delete();
        } else {
            $apiData->message = "删除失败";
            $apiData->code    = "3027";
        }
        return $apiData->send();
    }


    /**
     * 修改读书会会员信息
     * */
    public function update_read_party_member(Request $request)
    {

        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $departmentId = $request->input('departmentId');
        $readPartyId  = $request->input('readPartyId');
        $job          = $request->input('job');
        $isEmployee   = $request->input('isEmployee', 0);
        $rewardRight  = $request->input('rewardRight');
        $userId       = $request->input('userId');
        $userMobile   = $request->input('userMobile');
        $apiData      = new ApiData();

        $params = [
            'departmentId' => [$departmentId, '缺少部门ID', '2003'],
            'job'          => [$job, '缺少工作名称', '2004'],
            'userMobile'   => [$userMobile, '修改的手机号为空', '2006'],
            'userId'       => [$userId, '用户的ID为空', '2007']
        ];


        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "2001";
            return $apiData->send();
        }


        $updatedUserInfo = $memberModel->get_member_info_by_id($userId);
        if ($updatedUserInfo == false) {
            $apiData->message = "被修改的用户不存在";
            $apiData->code    = "2002";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        $companyId      = $readPartyInfo->company_id;

        $companyModel = new CompanyModel();

        //判断状态 修改企业端口 和 员工有效时间
        if ($isEmployee == 0) { //离职处理

            //1.从读书会移除
            $readPartyModel->remove_party_member($readPartyId, $userId);

            //检查是否还存在本公司的其他读书会 如果不存在 则移出本公司
            $count = DB::table('read_party_member as a')
                ->leftJoin('read_party as b', 'b.ReaParID', '=', 'a.read_party_id')
                ->where('b.company_id', $companyId)
                ->where('a.read_party_id', '<>', $readPartyId)
                ->count();

            if ($count == 0) {  //不存在其他读书会 从公司删除 删除后自动恢复端口
                $companyModel->delete_company_member($companyId, $userId);
                $companyModel->change_member_endtime($userId);
            }
            $apiData->send('200', '删除成功');
        }

        //修改用户公司信息
        $companyMemberInfo = ['job' => $job, 'department_id' => $departmentId];
        $companyModel->update_company_member($userId, $companyId, $companyMemberInfo);

        //修改用户基本信息
        $modifyInfo = [
            'UserID'   => $updatedUserInfo->UserID,
            'UserName' => $userMobile
        ];
        $memberModel->update_member_info($modifyInfo);


        //修改读书会相关信息
        $partyMemberInfo = ['reward_right' => $rewardRight,'department_id'=>$departmentId];
        $readPartyModel->update_read_party_member($readPartyId, $userId,$partyMemberInfo);
        return $apiData->send("200", "修改成功");
    }






    /*========= 5.读书会的读书信息 =============*/
    /* 读书改进计划：是指会员在观看视频的时候，同时在输入栏里写入的当时的一些所得和感受
     * 评论：是指其他会员给读书改进计划下做的评论
     * 打赏：是指其他成员读书改进计划者的金币打赏
     * */

    /**
     * 获得单条读书计划信息
     *
     */
    public function get_read_plan_info(Request $request)
    {

        $apiData     = new ApiData();
        $readPlanId  = $request->input('commentId');
        $readPartyId = $request->input('readPartyId');
        $mobile      = $request->input('mobile');
        $appKey      = $request->input('key');

        $params = [
            "mobile"      => [$mobile, "手机号为空"],
            "key"         => [$appKey, "APP设备ID为空"],
            "readPartyId" => [$readPartyId, "读书会ID为空"],
            "readPlanId"  => [$readPlanId, "读书改进计划ID为空"]
        ];


        $paramsCheck = $this->check_params($params);
        if ($paramsCheck->status == false) {
            $apiData->message = $paramsCheck->message;
            $apiData->code    = "400";
            return $apiData->send();
        }

        $userModel = new MemberModel();
        $userInfo  = $userModel->get_member_info_by_mobile_key($mobile, $appKey);
        if ($userInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "401";
            return $apiData->send();
        }


        $bookModel    = new BookModel();
        $readPlanInfo = $bookModel->get_comment_info($readPlanId);

        unset($readPlanInfo->UserID);
        unset($readPlanInfo->UserName);
        unset($readPlanInfo->NickName);

        $readModel                 = new ReadPartyModel();
        $zanList                   = $readModel->get_read_plan_money_gift($readPlanId, $readPartyId); //取出该评论的打赏记录
        $readPlanInfo->zan         = $zanList;
        $comments                  = $readModel->get_read_plan_comment($readPlanId, $readPartyId); //评论
        $readPlanInfo->commentlist = $comments;
        $apiData->message          = "ok";
        $apiData->code             = "200";
        $apiData->set_data('data', $readPlanInfo);
        return $apiData->send_old();
    }


    public function get_user_book_read_plan(Request $request)
    {

        $apiData = new ApiData();
        $mobile  = $request->input('mobile');
        $appKey  = $request->input('key');

        $bookId      = $request->input('bookId');
        $userId      = $request->input('friendUserId');
        $readPartyId = $request->input('readPartyId');

        $params = [
            "mobile"      => [$mobile, "手机号为空"],
            "key"         => [$appKey, "APP设备ID为空"],
            "readPartyId" => [$readPartyId, "读书会ID为空"],
            "bookId"      => [$bookId, "缺少书籍ID"],
            "userId"      => [$userId, "缺少好友的用户ID"]
        ];

        $paramsCheck = $this->check_params($params);
        if ($paramsCheck->status == false) {
            $apiData->message = $paramsCheck->message;
            $apiData->code    = "400";
            return $apiData->send();
        }

        $userModel = new MemberModel();
        $userInfo  = $userModel->get_member_info_by_mobile_key($mobile, $appKey);
        if ($userInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "401";
            return $apiData->send();
        }

        $friendUserInfo = $userModel->get_member_info_by_id($userId);

        $bookModel    = new BookModel();
        $readPlanInfo = $bookModel->get_user_book_read_plan($bookId, $friendUserInfo->MemNumber);
        if (!$readPlanInfo) {
            return $apiData->send('4002', '没有读书改进计划');
        }
        $readPlanId   = $readPlanInfo->SumUpID;
        $readPlanInfo = $bookModel->get_comment_info($readPlanId);
        unset($readPlanInfo->UserName);
        unset($readPlanInfo->NickName);


        $commentReply = new CommentReply();
        $readModel    = new ReadPartyModel();

        //1.根据读书的ID 判断是否用户进入的是企业还是个人
        $bookType = DB::table('read_party')
            ->where('ReaParID', $readPartyId)
            ->pluck('ReaParType')
            ->toArray();

        $readPlanInfo->isLike = preg_match("/$mobile/", $readPlanInfo->is_like_users) ? 1 : 0;

        //2.根据$bookType的类型进行判断是企业还是个人如果是企业
        if ($bookType[0] == 1) {//企业类型
            $zanList = $readModel->get_read_plan_money_gift($readPlanId, $readPartyId);
            //取出该评论的打赏记录
            $readPlanInfo->zan = $zanList;

        } else if ($bookType[0] == 2) {//个人类型
            //1.获取所有点赞的用户
            $isLikeUsers = $readPlanInfo->is_like_users;
            $isLikeUsers = explode(',', $isLikeUsers);
            unset($isLikeUsers[0]);
            if ($isLikeUsers) {
                foreach ($isLikeUsers as $k => $v) {
                    $userData = DB::table('memberinfo')->where(['UserName' => $v, 'DeleteMark' => 1])->first(['YourName', 'UserID']);
                    if ($userData) {
                        $readPlanInfo->zan[] = $userData;
                    }
                }
            } else {
                $readPlanInfo->zan = [];
            }
        }
        $comments                  = $commentReply->getPlayComment($readPlanId, $readPartyId); //评论
        $readPlanInfo->commentlist = $comments;
        $bookInfo                  = $bookModel->get_book_info($bookId);
        //1.添加读书会的类型1为企业的读书会 2为个人的读书会
        $type      = $bookType[0] == 1 ? 1 : 2;//1为企业2为个人
        $companyId = $this->getCompanyIdByReadPartId($readPartyId);
        $hasDrp    = $this->hasDrp($mobile, $appKey,$companyId);
        $hasAdmin  = $this->hasAdmin($readPartyId, $userInfo->MemNumber);
        if ($hasAdmin) {
            $isAdmin = 1;//管理员
        } else if ($hasDrp) {
            $isAdmin = 2;//学习官
        } else {
            $isAdmin = 0;//普通人
        }
        return $apiData->set_data('bookInfo', $bookInfo)
            ->set_data('readPlanInfo', $readPlanInfo)
            ->set_data('isAdmin', $isAdmin)
            ->set_data('type', $type)
            ->send('200', 'ok');
    }


    /**
     * （一本书在某个俱乐部会员下的）全部评论
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sumupComment(Request $request)
    {
        $result = 'no';
        $rules  = [
            'id'     => 'required',
            'type'   => 'required',
            'parid'  => 'required',
            'mobile' => 'required',
            'key'    => 'required'
        ];

        $messages = [
            'id.required'     => '2039',
            'type.required'   => '2094',
            'parid.required'  => '2093',
            'mobile.required' => '2037',
            'key.required'    => '2038'
        ];
        $id       = $request->input('id');
        $type     = $request->input('type');
        $parid    = $request->input('parid');
        $mobile   = $request->input('mobile');
        $key      = $request->input('key');


        $params = [
            'mobile' => $mobile,
            'key'    => $key,
            'id'     => $id,
            'type'   => $type,
            'parid'  => $parid
        ];


        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        $member = $this->memNumber($mobile, $key);
        if ($member) {
            $entBookSumUp = DB::table('vw_app_booksumup')
                ->select('SumUpID', 'UserName', 'FilePath1', 'YourName', 'BookReview1', 'BookReview2', 'BookReview3', 'BookReview4', 'commsum1', 'commsum2', 'commsum3', 'commsum4', 'AddDate')
                ->where('SumUpID', $id)
                ->first();

            if ($entBookSumUp) {

                $content = '';
                $commsum = '0';
                switch ($type) {
                    case 1:
                        $content = $entBookSumUp->BookReview1;
                        $commsum = $entBookSumUp->commsum1;
                        break;
                    case 2:
                        $content = $entBookSumUp->BookReview2;
                        $commsum = $entBookSumUp->commsum2;
                        break;
                    case 3:
                        $content = $entBookSumUp->BookReview3;
                        $commsum = $entBookSumUp->commsum3;
                        break;
                    case 4:
                        $content = $entBookSumUp->BookReview4;
                        $commsum = $entBookSumUp->commsum4;
                        break;
                }
                //是否点赞过
                $checkZan = EntCommZanLog::select('ZanID')->where('MemNumber', $member->MemNumber)->where('Type', $type)->where('CommID', $id)->first();
                $zancolor = 0;
                if ($checkZan) {
                    $zancolor = 1;
                }
                //改进计划详细
                $sunupdetail = ['id' => $entBookSumUp->SumUpID, 'name' => $entBookSumUp->YourName, 'url' => $entBookSumUp->FilePath1, 'content' => $content, 'commsum' => $commsum, 'zancolor' => $zancolor, 'time' => $entBookSumUp->AddDate];
                //评论列表
                $entCommentReply = DB::table('vw_app_commentreply')->select('RepID', 'AddDate', 'CommContents', 'YourName', 'FilePath1', 'commsum')->where('States', '1')->where('DeleteMark', '1')->where('ReaParID', $parid)->where('CommID', $id)->where('Type', $type)->orderBy('AddDate', 'desc')->simplePaginate(6);
                return response()->json(['message' => 'ok', 'code' => '200', 'sunupdetail' => $sunupdetail, 'replylist' => $entCommentReply]);
            } else {
                //改进计划不存在
                return response()->json(['message' => $result, 'code' => '3073']);
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3027']);
        }
    }


    /**
     * 添加对读书改进计划的评论
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_read_plan_comment(Request $request)
    {
        $result = 'no';
        $rules  = [
            'id'      => 'required',
            'type'    => 'required',
            'parid'   => 'required',
            'content' => 'required',
            'mobile'  => 'required',
            'key'     => 'required',
        ];

        $messages = [
            'id.required'      => '2039',
            'type.required'    => '2094',
            'parid.required'   => '2093',
            'content.required' => '2095',
            'mobile.required'  => '2037',
            'key.required'     => '2038',
        ];

        $id      = $request->input('id');//父级ID  |booksumup用户读书改进计划的主键ID
        $mobile  = $request->input('mobile');//手机号
        $type    = $request->input('type');//默认为0就可以
        $parid   = $request->input('parid');//读书会ID
        $content = $request->input('content');//评论的内容
        $key     = $request->input('key');//设备的ID
        $params  = [
            'mobile'  => $mobile,
            'key'     => $key,
            'id'      => $id,
            'type'    => $type,
            'parid'   => $parid,
            'content' => $content,
        ];
        $v       = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        $memberModel = new MemberModel(); //会员信息的Model
        $member      = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($member == false) {
            return response()->json(['message' => $result, 'code' => '3027']);//如果用户手机没有会员信息则没有登录
        }

        $entCommentReply               = new EntCommentReply();//回复读书改进计划的评论
        $entCommentReply->States       = 1;
        $entCommentReply->Type         = $type;
        $entCommentReply->CommContents = emoji_text_encode($content);
        $entCommentReply->CommID       = $id;//读书改进计划的内容的ID
        $entCommentReply->ReaParID     = $parid;//读书会的ID【对应的是read_party】
        $entCommentReply->MemNumber    = $member->MemNumber;
        $entCommentReply->DeleteMark   = 1;//是否已经删除1为没有删除0为已经删除了
        $entCommentReply->ReleaseDate  = date('Y-m-d H:i:s', time());//添加的时间
        $entCommentReply->AddDate      = date('Y-m-d H:i:s', time());//添加的时间
        $entCommentReply->save();

        if ($entCommentReply) {

            $bookModel    = new BookModel();//获取书籍的信息
            $readPlanOwer = $bookModel->get_comment_info($id);//获取摸一个读书改进计划的ID

            //添加消息
            $messageCtrl = new MessageModel();
            $msg         = '读书改进评论:您的好友' . $member->YourName . "评论了你的《" . $readPlanOwer->BookTitle . "》读书改进计划日志";
            $msgId       = $messageCtrl->add_note_message("读书改进评论", $msg);
            $messageCtrl->add_user_message($msgId, $readPlanOwer->UserID);


            //发送消息
            $push        = new Jpush();
            $push->alias = $readPlanOwer->UserName;
            $push->set_message($msg);
            $push->send();
            return response()->json(['message' => 'ok', 'code' => '200']);
        } else {
            //评论失败
            return response()->json(['message' => $result, 'code' => '3074']);
        }

    }




    /**
     * 获取某本书在某读书会下的所有会员的读书改进计划
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function read_party_book_gift(Request $request)
    {
        $apiData      = new ApiData();
        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $parid        = $request->input('parid');
        $page         = $request->input('page');
        $bookId       = $request->input('bookId');
        $departmentId = $request->input('departmentId');

        $params = [
            'mobile' => [$mobile, "缺少手机号", "2037"],
            'key'    => [$key, "缺少APP设备ID", "2038"],
            'parid'  => [$parid, "缺少读书会ID", "6005"],
            'bookId' => [$bookId, "缺少书籍ID", "2039"]
        ];

        $paramsCheck = $this->check_params($params);
        if ($paramsCheck->status == false) {
            $apiData->message = $paramsCheck->message;
            $apiData->code    = $paramsCheck->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }


        $bookModel        = new BookModel();
        $planGift         = $bookModel->get_read_plan_by_book_readparty($bookId, $parid, $departmentId);
        $apiData->message = "ok";
        $apiData->code    = "200";
        $apiData->set_data('pagelist', $planGift);
        return $apiData->send_old();

    }


    /**
     * 会员信息
     * @param string $mobile
     * @param string $key
     * @return mixed
     */
    protected function memNumber($mobile = '', $key = '')
    {
        $memberModel   = new EntMemberInfo();
        $entMemberInfo = $memberModel->get_member_info_by_mobile_and_appkey($mobile, $key);
        return $entMemberInfo;
    }


    protected function memNumberTwo($memid = '')
    {

        $entMemberInfo = EntMemberInfo::select('States', 'MemEndTime', 'FilePath1', 'YourName', 'MemNumber')->where('DeleteMark', '1')->where('MemNumber', $memid)->first();
        return $entMemberInfo;
    }



    //======================================v2 end ==========================
    //添加评论
    public function addComment(Request $request)
    {
        //获取memberinfor表里面的MemNumber---用户唯一的信息;
        $memberModel = new MemberModel();
        $mobile      = $request->mobile;//用户的手机号;
        $key         = $request->key;
        $userInfo    = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        //判断用户信息是否存在
        if (!$userInfo) {
            return $this->response->array(['code' => '404', 'message' => '用户不存在', 'data' => []]);
        }
        $memNumber = $userInfo->MemNumber;
        if ($memNumber == $request->reply_MemNumber) {
            return $this->response->array(['code' => '403', 'message' => '您不能回复自己', 'data' => []]);
        }

        $addParams = [
            'MemNumber'  => $memNumber,
            'DeleteMark' => 1
        ];
        $request->merge($addParams);
        $params                 = $request->all();
        $params['CommContents']   = emoji_text_encode($params['CommContents']);
        $validateMessage = $this->checkUserInput($params);
        if ($validateMessage->fails()) {//用户输入验证失败
            return $this->response->array([
                'code'    => 400,
                'message' => '参数错误',
                'data'    => $validateMessage->messages()
            ]);
        };
        $commentOrReply = CommentReply::create($params);//添加数据

        if ($commentOrReply) {//用户添加评论或者回复成功
            $sumUpUserId   = $request->sumup_user_id;//评论读书会的---写这个读书会的ID
            $commentUserId = $request->comment_user_id;//回复评论的用户的ID

            //去除返回的接口数据
            unset($params['mobile']);
            unset($params['key']);

            $data = CommentReply::where('RepID', $commentOrReply->id)
                ->select('commentreply.*', 'm.UserID', 'm.YourName as userName', 'm.FilePath1 as userAvg', 'mm.UserID as replyUserId', 'mm.YourName as replyName')
                ->join('memberinfo as m', 'm.MemNumber', '=', 'commentreply.MemNumber')
                ->leftJoin('memberinfo as mm', 'commentreply.reply_MemNumber', '=', 'mm.MemNumber')
                ->first();

            $data->userAvg      = change_member_head_img($data->userAvg);
            $data->CommContents = emoji_text_decode($data->CommContents);


            //极光推送
            //1.自己评论自己的读书改进计划不进行极光推送-----已经不在读书会的不要进行推送
            $memNumber2 = DB::table('booksumup')->where('SumUpID', $request->CommID)->first(['MemNumber']);
            $memNumber2 = $memNumber2->MemNumber;

            if ($memNumber != $memNumber2) {//当用户评论的不是自己的读书改进计划或者是不是评论自己的自己的评论
                $reply_user_info    = DB::table('memberinfo')
                    ->select('UserName')
                    ->where('MemNumber', $request->reply_MemNumber)
                    ->first();
                $request_user_phone = $reply_user_info ? $reply_user_info->UserName : null;//是否可以获取回复用户的手机号
                //1.判断当前写读书计划这个人是否还在这个读书会
                $is_belong_read_party_sum = $this->is_belong_read_department($request->ReaParID, $sumUpUserId);
                $sumUpUserId              = $is_belong_read_party_sum ? $sumUpUserId : null;
                //2.判断写评论这个用户是否还在这个读书会

                $is_belong_read_party_comment = $this->is_belong_read_department($request->ReaParID, $commentUserId);
                $commentUserId                = $is_belong_read_party_comment ? $commentUserId : null;
                if ($sumUpUserId || $commentUserId) {//如果用户还在这个读书会
                    //事件推送
                    $noticeInfo = event(new NoticeUserEvent(
                        $sumUpUserId,//要通知用户的UserId写这个读书会的User_ID
                        $commentUserId,//要通知用户的userID回复评论的用户的USER_ID
                        $request->CommID,//读书改进计划的ID
                        $request->ReaParID,
                        $userInfo->YourName,
                        $userInfo->FilePath1,
                        $request->CommContents));
                    //获取用户单本书的读书改进计划 接口参数
                    $booksumupData    = DB::table('booksumup')
                        ->where('SumUpID', $request->CommID)
                        ->select('BookID', 'MemNumber', 'BookReview1')
                        ->first();
                    $bookUserId       = $this->getUserIdByMemNumber($booksumupData->MemNumber);
                    $bookId           = $booksumupData->BookID;
                    $bookReview       = $booksumupData->BookReview1;
                    $bookData         = [
                        'bookId'        => $bookId,
                        'firendUserId'  => $bookUserId,
                        'read_party_id' => $request->ReaParID,
                        'noticeId'      => $noticeInfo[0]->id,//表示该通知的问题的唯一的标识
                        'avg'           => $noticeInfo[0]->avg,
                        'userName'      => $noticeInfo[0]->user_name,
                        'sum_up_id'     => $noticeInfo[0]->sum_up_id,
                        'publish_at'    => Carbon::parse($noticeInfo[0]->created_at)->diffForHumans(),
                        'content'       => $noticeInfo[0]->content,
                        'bookReview'    => $bookReview
                    ];
                    $readPlayData     = [
                        'code'    => 201,//添加评论
                        'message' => json_encode($bookData)
                    ];
                    $publish_at       = Carbon::parse($noticeInfo[0]->created_at)->diffForHumans();
                    $commentUserInfo  = DB::table('memberinfo')->select('UserName')
                        ->where('MemNumber', $memNumber2)
                        ->first();
                    $commentUserPhone = $commentUserInfo->UserName;
                }

//                ============极光推送==============================

                //1.判断是否是评论还是回复
                if (!$request_user_phone && $sumUpUserId != null) {//如果是评论---通知写读书改进计划的这个人
                    $this->JpushContent($userInfo->YourName . '评论了你的读书改进计划', $commentUserPhone, $userInfo->YourName , $readPlayData);
                } else {//如果是回复---通知写评论的那个人
                    if ($commentUserPhone != $request_user_phone) {
                        if ($sumUpUserId != null) {
                            $this->JpushContent($userInfo->YourName . '评论了你的读书改进计划', $commentUserPhone, $userInfo->YourName , $readPlayData);
                        }
                        if ($commentUserId != null) {
                            $this->JpushContent($userInfo->YourName . '回复了你的评论', $request_user_phone, $userInfo->YourName, $readPlayData);
                        }
                    } else {
                        if ($sumUpUserId != null) {
                            $this->JpushContent($userInfo->YourName . '评论了你的读书改进计划', $commentUserPhone, $userInfo->YourName, $readPlayData);
                        }
                    }
                }
            } elseif ($memNumber != $request->reply_MemNumber && $memNumber == $memNumber2 && $request->reply_MemNumber != 0) {//是自己的读书改进计划---但是回复人不是自己
                $reply_user_info    = DB::table('memberinfo')
                    ->select('UserName')
                    ->where('MemNumber', $request->reply_MemNumber)
                    ->first();
                $request_user_phone = $reply_user_info ? $reply_user_info->UserName : null;//是否可以获取回复用户的手机号

                //1.判断写评论这个用户是否还在这个读书会
                $is_belong_read_party_comment = $this->is_belong_read_department($request->ReaParID, $commentUserId);
                $commentUserId                = $is_belong_read_party_comment ? $commentUserId : null;
                //事件推送
                $noticeInfo = event(new NoticeUserEvent(
                    null,//要通知用户的UserId
                    $commentUserId,//要通知用户的userID
                    $request->CommID,//读书改进计划的ID
                    $request->ReaParID,
                    $userInfo->YourName,
                    $userInfo->FilePath1,
                    $request->CommContents));

                if ($commentUserId != null) {//如果用户还在这个读书会
                    //获取用户单本书的读书改进计划 接口参数
                    $booksumupData = DB::table('booksumup')
                        ->where('SumUpID', $request->CommID)
                        ->select('BookID', 'MemNumber', 'BookReview1')
                        ->first();
                    $bookUserId    = $this->getUserIdByMemNumber($booksumupData->MemNumber);
                    $bookId        = $booksumupData->BookID;
                    $bookReview    = $booksumupData->BookReview1;
                    $bookData      = [
                        'bookId'        => $bookId,
                        'firendUserId'  => $bookUserId,
                        'read_party_id' => $request->ReaParID,
                        'noticeId'      => $noticeInfo[0]->id,//表示该通知的问题的唯一的标识
                        'avg'           => $noticeInfo[0]->avg,
                        'userName'      => $noticeInfo[0]->user_name,
                        'sum_up_id'     => $noticeInfo[0]->sum_up_id,
                        'publish_at'    => Carbon::parse($noticeInfo[0]->created_at)->diffForHumans(),
                        'content'       => $noticeInfo[0]->content,
                        'bookReview'    => $bookReview
                    ];
                    $readPlayData  = [
                        'code'    => 201,//添加评论
                        'message' => json_encode($bookData)
                    ];
                    $publish_at    = Carbon::parse($noticeInfo[0]->created_at)->diffForHumans();

                    $this->JpushContent($userInfo->YourName . '回复了你的评论', $request_user_phone, $userInfo->YourName, $readPlayData);
                }
            }

            //给评论或回复添加积分
            $memberModel->add_member_integral($userInfo->UserID,2,$commentOrReply->id,"评论或回复读书改进计划");

            //判断用户的添加的数据是那种类型
            $message = $params['reply_MemNumber'] ? '添加回复成功' : '添加评论成功';

            return $this->response->array(['code' => 200, 'message' => $message, 'data' => $data]);
        }
        //用户添加评论或者回复失败
        return $this->response->array(['code' => 200, 'message' => '添加评价失败', 'data' => []]);
    }

    //删除某一条的评论
    public function delComment(Request $request)
    {
        $repid        = $request->repid;//commentreply的主键ID RepID
        $mobile       = $request->mobile;
        $key          = $request->key;
        $memberNumber = $request->memberNumber;//用户的唯一编号
        //1.判断用户的身份是否是管理员
        //(1)获取读书会的ID
        $commentreply = DB::table('commentreply')->where('RepID', $repid)->first();
        //(2)获取读书会的ID
        $readPartyId = $commentreply->ReaParID;
        $companyId   = $this->getCompanyIdByReadPartId($readPartyId);
        //(3)判断当前评论是否是当前用户
        $isOwnComment = $this->hasComment($memberNumber);
        $isAdmin      = $this->hasAdmin($readPartyId, $memberNumber);
        $isDrop       = $this->hasDrp($mobile, $key, $companyId);
        if ($isOwnComment || $isAdmin || $isDrop) {//如果是自己的评论允许自己删除 或者是管理员允许删除
            $status = CommentReply::where('RepID', $repid)->update(['DeleteMark' => 0]);
            $msg    = $status ? '删除成功' : '删除失败了';

            return $this->response->array(['code' => '200', 'msg' => $msg, 'data' => []]);
        };

        return $this->response->array(['code' => '403', 'msg' => '权限不足', 'data' => []]);
    }

    //读书改进计划页面的数据
    public function getImproveData(Request $request)
    {
        $apiData = new ApiData();
        $book    = $request->input('bookId', 0);
        $readId  = $request->input('readPartid');
        $mobile  = $request->input('mobile');
        $key     = $request->input('key');
        $params  = [
            'mobile' => [$mobile, "缺少手机号", "2037"],
            'key'    => [$key, "缺少设备ID", "2038"],
            'readId' => [$readId, "缺少读书会ID", "2039"]
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        //读取读书会
        $readPartyModel = new ReadPartyModel();


        $readPartyInfo = $readPartyModel->get_read_party_info($readId);
        if (!$readPartyInfo) { //读书会信息不存在
            $apiData->message = "读书会不存在";
            $apiData->code    = "3062";
            return $apiData->send();
        }
        $userReadInfo = $readPartyModel->get_read_party_member_detail($memberInfo->UserID, $readId);


        if (!$userReadInfo)
        {
            $apiData->message = "您没有参加该读书会";
            $apiData->code    = "3063";
            return $apiData->send();
        }

        $readPartyInfo->isEmployee      = 0;
        $readPartyInfo->rewardRight     = $userReadInfo->reward_right;
        $readPartyInfo->lookGiftRight   = $userReadInfo->look_gift_right;
        $bookModel                  = new BookModel();

        //读取最新书籍
        if ($book > 0) {
            $bookInfo = $bookModel->get_book_info($book);
        }
        if ($book == 0 || (!$bookInfo)) {
            $bookInfo = $bookModel->get_last_book_info();
        }
        $bookInfo->AddDate  = $bookInfo->publish_date;
        $bookInfo->bookurl  = $bookInfo->FilePath1;

        //添加用户通知的模块
        //1.获取到所有的这个人这个读书会的所有的未读的信息
        $noticeUserInfo = DB::table('notice_user')
            ->where(['read_party_id' => $readId, 'notice_user_id' => $memberInfo->UserID, 'deleted_at' => null])
            ->orderBy('created_at', 'desc')
            ->get();
        $noticeData     = [];
        $tmp            = [];
        foreach ($noticeUserInfo as $k => $v) {
            $tmp['noticeId']      = $v->id;
            $tmp['avg']           = change_member_head_img($v->avg);
            $tmp['userName']      = $v->user_name;
            $xxx                  = DB::table('booksumup')->select('BookReview1', 'BookID', 'MemNumber')->where('SumUpID', $v->sum_up_id)->first();
            $tmp['bookReview']    = $xxx->BookReview1;
            $tmp['sum_up_id']     = $v->sum_up_id;
            $tmp['read_party_id'] = $v->read_party_id;
            $tmp['publish_at']    = Carbon::parse($v->created_at)->diffForHumans();
            $tmp['content']       = emoji_text_decode($v->content);
            $tmp['bookId']        = $xxx->BookID;
            $bookSumupUserId     = $this->getUserIdByMemNumber($xxx->MemNumber);
            $tmp['firendUserId'] = $bookSumupUserId;
            array_push($noticeData, $tmp);
        }
        $readPartyInfo->noticeInfo = $noticeData;


        //验证是否有修改头像权限 1-是 0-否
        $isAdmin   = $memberInfo->MemNumber == $readPartyInfo->MemNumber ? 1 : 0;
        $companyId = $this->getCompanyIdByReadPartId($readId);
        $isDrp     = $this->hasDrp($mobile, $key, $companyId);
        if ($isAdmin) {//如果是管理员
            $readPartyInfo->isAdmin = $isAdmin;
        } else {
            $readPartyInfo->isAdmin = $isDrp ? 2 : 0;
        }





        //1.根据读书的ID 判断是否用户进入的是企业还是个人
        $bookType = DB::table('read_party')->where('ReaParID', $readId)->pluck('ReaParType')->toArray();
        $type     = $bookType[0];
        //读书改进计划
        $bookSumup = $bookModel->get_read_plan_by_book_readparty($bookInfo->BookID, $readId, null, $type);

        foreach ($bookSumup as $data) {
            $data->BookTitle = $bookInfo->BookTitle;
            $commentId       = $data->SumUpID;
            //2.根据$bookType的类型进行判断是企业还是个人如果是企业
            if ($bookType[0] == 1) {//企业类型
                $data->zan = $readPartyModel->get_read_plan_money_gift($commentId, $readId);     //取出打赏记录
            } else if ($bookType[0] == 2) {//个人类型
                $data->isLike = preg_match("/$mobile/", $data->is_like_users) ? 1 : 0;
                //1.获取所有点赞的用户
                $isLikeUsers = $data->is_like_users;
                $isLikeUsers = explode(',', $isLikeUsers);
                unset($isLikeUsers[0]);
                if ($isLikeUsers) {
                    foreach ($isLikeUsers as $k => $v) {
//                        $userData = DB::table('memberinfo')->where(['UserName' => $v, 'DeleteMark' => '1'])->first(['YourName', 'UserID']);
                        $userData = $bookModel->get_persons_zan($v, $readId);
                        if ($userData) {
                            $data->zan[] = $userData;
                        }
                    }
                } else {
                    $data->zan = [];
                }
            }
            $data->ReleaseDate  = $data->AddDate;
            $data->commentlist = $this->getAllComments($commentId, $readId); //评论 readId 读书会的ID commenId读书改进计划的ID
        }

        $memberMoney   = $readPartyModel->get_member_money($memberInfo->MemNumber, $readId);        //登录者获得的金币
        $totalOutMoeny = $readPartyModel->get_total_out_money($memberInfo->MemNumber, $readId);   //登录者打赏出去的金币

        //企业组织架构 organization
        $organization = [];
        $companyInfo  = [];
        $comDepart    = [];

        if ($readPartyInfo->ReaParType == 1) {
            $companyId = $readPartyInfo->company_id;
            if ($companyId > 0) { //没有公司的，分到未分组里面去
                $companyModel = new CompanyModel();
                $companyInfo  = $companyModel->get_company_info($companyId);
                $departments  = $companyModel->get_company_department($companyId,$readId);

                foreach ($departments as $depart) {
                    $partInfo = [
                        'departmentName' => $depart->department_name,
                        'members'        => [],
                        'departmentId'   => $depart->department_id
                    ];
                    array_push($comDepart, $partInfo);
                }
            }
        }

        $organization['companyInfo'] = $companyInfo;
        $organization['deparments']  = $comDepart;

        $readPartyInfo->outMoney    = $totalOutMoeny;
        $readPartyInfo->memberMoney = $memberMoney;
        $readPartyInfo->maxRewardMoney = (int) system_log('max_reward_money');//最多打赏金额

        return $apiData
            ->set_data('bookInfo', $bookInfo)
            ->set_data('readPartyInfo', $readPartyInfo)
            ->set_data('organization', $organization)
            ->set_data('readPlanList', $bookSumup)
            ->send("200","ok");
    }

    //获取单条的读书改进计划的信息
    public function getReadPlanInfo(Request $request)
    {

        $apiData     = new ApiData();
        $readPlanId  = $request->input('commentId');
        $readPartyId = $request->input('readPartyId');
        $mobile      = $request->input('mobile');
        $appKey      = $request->input('key');

        $params = [
            "mobile"      => [$mobile, "手机号为空"],
            "key"         => [$appKey, "APP设备ID为空"],
            "readPartyId" => [$readPartyId, "读书会ID为空"],
            "readPlanId"  => [$readPlanId, "读书改进计划ID为空"]
        ];


        $paramsCheck = $this->check_params($params);
        if ($paramsCheck->status == false) {
            $apiData->message = $paramsCheck->message;
            $apiData->code    = "400";
            return $apiData->send();
        }

        $userModel = new MemberModel();
        $userInfo  = $userModel->get_member_info_by_mobile_key($mobile, $appKey);
        if ($userInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "401";
            return $apiData->send();
        }


        $bookModel    = new BookModel();
        $readPlanInfo = $bookModel->get_comment_info($readPlanId);
//        unset($readPlanInfo->UserID);
        unset($readPlanInfo->UserName);
        unset($readPlanInfo->NickName);

        $commentReply = new CommentReply();
        $readModel    = new ReadPartyModel();

//        $zanList                   = $readModel->get_read_plan_money_gift($readPlanId, $readPartyId);
//        //取出该评论的打赏记录
//        $readPlanInfo->zan         = $zanList;

        //1.根据读书的ID 判断是否用户进入的是企业还是个人
        $bookType = DB::table('read_party')->where('ReaParID', $readPartyId)->pluck('ReaParType')->toArray();
        //2.根据$bookType的类型进行判断是企业还是个人如果是企业
        if ($bookType[0] == 1) {//企业类型
            $zanList = $readModel->get_read_plan_money_gift($readPlanId, $readPartyId);
            //取出该评论的打赏记录
            $readPlanInfo->zan    = $zanList;
            $readPlanInfo->isLike = 0;

        } else if ($bookType[0] == 2) {//个人类型

            $readPlanInfo->isLike = preg_match("/$mobile/", $readPlanInfo->is_like_users) ? 1 : 0;
            //1.获取所有点赞的用户
            $isLikeUsers = $readPlanInfo->is_like_users;
            $isLikeUsers = explode(',', $isLikeUsers);
            unset($isLikeUsers[0]);
            if ($isLikeUsers) {
                foreach ($isLikeUsers as $k => $v) {
//                    $userData = DB::table('memberinfo')->where(['UserName' => $v, 'DeleteMark' => '1'])->first(['YourName', 'UserID', 'UserName']);
                    $userData = $bookModel->get_persons_zan($v, $readPartyId);
                    if ($userData) {
                        $readPlanInfo->zan[] = $userData;
                    }
                }
            } else {
                $readPlanInfo->zan = [];
            }
        }
        $comments                  = $commentReply->getPlayComment($readPlanId, $readPartyId); //评论
        $readPlanInfo->commentlist = $comments;
        $apiData->message          = "ok";
        $apiData->code             = "200";
        $apiData->set_data('data', $readPlanInfo);
        return $apiData->send_old();
    }

    //用户点赞
    public function isLike(Request $request)
    {
        $SumUpID       = $request->sumUpID;//读书改进计划的ID
        $mobile        = $request->mobile;
        $devKey        = $request->key;
        $sumup_user_id = $request->sumup_user_id;
        $memberModel   = new MemberModel();
        $userInfo      = $memberModel->get_member_info_by_mobile_key($mobile, $devKey);

        if (!$userInfo) {
            return $this->response->array(['code' => "404", 'message' => '用户不存在', 'data' => []]);
        }

        //(1)判断用户是否已经点过赞了
        $booksump = DB::table('booksumup')->where('SumUpID', $SumUpID)->first();
        $data     = explode(',', $booksump->is_like_users);
        if ($key = array_search($mobile, $data)) {//如果已经存在则取消赞
            unset($data[$key]);
            $data = implode(',', $data);
            DB::table('booksumup')->where('SumUpID', $SumUpID)->update(['is_like_users' => $data]);
            return $this->response->array(['code' => '200', 'message' => '取消点赞成功', 'data' => []]);
        } else {//如果用户没有点赞则增加用户记录

            array_push($data, $mobile);//添加用户点赞到数据库
            $data = implode(',', $data);
            DB::table('booksumup')->where('SumUpID', $SumUpID)->update(['is_like_users' => $data]);

            //1.判断用户是否是自己点赞自己
            $userMobileMemNumber = $userInfo->MemNumber;//从用户表获取到memNumber;
            $sumpMemNumber       = DB::table('booksumup')->where('SumUpID', $SumUpID)->first(['MemNumber']);
            $sumpMemNumber       = $sumpMemNumber->MemNumber;

            if ($userMobileMemNumber != $sumpMemNumber) {//不是自己点赞自己则进行极光推送
                //事件监听用户通知模块
                $content = $userInfo->YourName . '赞了你的读书改进计划';
                event(new NoticeUserEvent(
                    $sumup_user_id,//写读书改进计划的用户的Id
                    null,
                    $SumUpID,//读书改进计划的Id
                    $request->ReaParID,//读书会的ID
                    $userInfo->YourName,
                    $userInfo->FilePath1,
                    $content));
//                //极光推送
//                $msg   = '点赞成功';
//                $title = '点赞';
//                $this->JpushSend($SumUpID, $userInfo, $msg, $title);
            }
            return $this->response->array(['code' => '200', 'message' => '点赞成功', 'data' => []]);
        }
    }

    //用户打赏
    public function reward(Request $request)
    {
        define('_qiye_', 1);
        define('_geren_', 2);

        $apiData     = new ApiData();
        $readPartyId = $request->input('id');
        $type        = $request->input('type');
        $memid       = $request->input('memid');
        $amount      = $request->input('amount');
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');
        $commentId   = $request->input('commentId');
        $sign        = $request->input('sign');
        $timestamp   = $request->input('timestamp');
        $params      = [
            'mobile'    => [$mobile, "缺少手机号", "2037"],
            'key'       => [$key, "缺少设备ID", "2038"],
            'id'        => [$readPartyId, "缺少读书会ID", "2103"],
            'type'      => [$type, "缺少打赏类型", "2104"],
            'memid'     => [$memid, "缺少会员编号", "2105"],
            'amount'    => [$amount, "缺少打赏数量", "2106"],
            'commentId' => [$commentId, "缺少读书计划ID", "2109"]
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "会员不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }


        //1.不能自己给自己打赏
        if ($memberInfo->MemNumber == $memid) {
            $apiData->message = "不能给自己打赏";
            $apiData->code    = "3100";
            return $apiData->send();
        }

        //2.检查读书会是否存在
        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        if ($readPartyInfo == false) {
            $apiData->message = "读书会不存在";
            $apiData->code    = "3095";
            return $apiData->send();
        }

        $readPartyType = $readPartyInfo->ReaParType;

        $adminAward = false;         //属于管理员打赏 打赏者和读书会管理员是同一个人
        if ($readPartyType == _geren_) {
            if ($readPartyInfo->MemNumber = $memberInfo->MemNumber) {
                $adminAward = true;
            }
        } elseif ($readPartyType == _qiye_) {
            $adminAward = $readPartyModel->check_have_award_right($readPartyId, $memberInfo->UserID);
        }


//        if ($adminAward) { /*特指管理员打赏 管理员打赏不用考量剩余的学习币是否足够*/
        //添加会长打赏记录 日志打赏记录信息
//            $logMsg    = '打赏会员 ' . $amount . ' 个学习币。';
//            $beiLogMsg = '被会长打赏获得 ' . $amount . ' 个学习币。';
//        } else { //会员之间互相打赏
        //该会员在本读书会的学习币
        $readPartyMoney = $readPartyModel->get_member_money($memberInfo->MemNumber, $readPartyId);
        if ($readPartyMoney < $amount && $adminAward == false) {
            $apiData->message = "您的学习币不足";
            $apiData->code    = "3089";
            return $apiData->send();
        }
        //添加打赏记录 日志打赏记录信息
        $logMsg    = '打赏会员扣除 ' . $amount . ' 个学习币。';
        $beiLogMsg = '被会员打赏获得 ' . $amount . ' 个学习币。';
//        }

        //会员之间互相打赏
//        if ($type == 3) {
//
//        } elseif ($type == 4) {    /*特指管理员打赏 管理员打赏不用考量剩余的学习币是否足够*/
//
//        }

        //学习币获得者的信息
        $memberInfoGeter = $memberModel->get_member_info_by_member_number($memid); //获得学习币的人的信息


        //5.1添加会员的总的学习币
        $result = $readPartyModel->add_read_plan_money($readPartyId, $memberInfoGeter->MemNumber, $amount);

        //5.2不是会长，扣除打赏者的学习币
//        if ($adminAward == false) {
        $readPartyModel->add_read_plan_money($readPartyId, $memberInfo->MemNumber, -$amount);
//        }


        //5.3添加学习币改变日志
        $arawLogData = [
            'MoReLoType'    => $type,
            'read_party_id' => $readPartyId,
            'MemNumber'     => $memberInfo->MemNumber,
            'BeiMemNumber'  => $memberInfoGeter->MemNumber,
            'MoReLoMoney'   => $amount,
            'MoReLoDesc'    => $logMsg,
            'MoReLoBeiDesc' => $beiLogMsg,
        ];
        $logId       = $readPartyModel->add_money_change_log($arawLogData);

        //5.4添加评论的打赏记录
        $giftData = [
            'comment_id'    => $commentId,
            'user_id'       => $memberInfo->UserID,
            'money'         => $amount,
            'read_party_id' => $readPartyId,
            'money_log_id'  => $logId
        ];
        $readPartyModel->add_read_plan_money_gift($giftData);

        //5.5推送消息 与 添加消息
        $bookModel   = new BookModel();
        $commentInfo = $bookModel->get_comment_info($commentId);
        $title       = "打赏学习币";
//        $msg          = $memberInfo->YourName . "给你的《" . $commentInfo->BookTitle . "》读书改进计划打赏了" . $amount . "个学习币!";
        $msg          = $memberInfo->YourName . "给你的读书改进计划打赏了" . $amount . "个学习币!";
        $messageModel = new MessageModel();
        $msgId        = $messageModel->add_note_message($title, $msg);
        $messageModel->add_user_message($msgId, $memberInfoGeter->UserID);

        //事件监听用户通知模块
        $noticeInfo = event(new NoticeUserEvent(
            $memberInfoGeter->UserID,//写读书改进计划的用户的Id
            null,
            $request->commentId,//读书改进计划的Id
            $request->id,//读书会的ID
            $memberInfo->YourName,
            $memberInfo->FilePath1,
            $msg));
        //获取用户单本书的读书改进计划 接口参数
        $booksumupData = DB::table('booksumup')
            ->where('SumUpID', $request->commentId)
            ->select('BookID', 'MemNumber', 'BookReview1')
            ->first();
        $bookUserId    = $this->getUserIdByMemNumber($booksumupData->MemNumber);
        $bookId        = $booksumupData->BookID;
        $bookReview    = $booksumupData->BookReview1;
        $bookData      = [
            'bookId'        => $bookId,
            'firendUserId'  => $bookUserId,
            'read_party_id' => $readPartyId,
            'noticeId'      => $noticeInfo[0]->id,//表示该通知的问题的唯一的标识
            'avg'           => $noticeInfo[0]->avg,
            'userName'      => $noticeInfo[0]->user_name,
            'sum_up_id'     => $noticeInfo[0]->sum_up_id,
            'publish_at'    => Carbon::parse($noticeInfo[0]->created_at)->diffForHumans(),
            'content'       => $noticeInfo[0]->content,
            'bookReview'    => $bookReview
        ];
        $readPlayData  = [
            'code'    => 202,//给用户打赏
            'message' => json_encode($bookData)
        ];
        $this->JpushContent($msg, $memberInfoGeter->UserName, $title, $readPlayData);
//        $jpush        = new Jpush();
//        $jpush->alias = $memberInfoGeter->UserName;
//        $jpush->set_message($msg);
//        $jpush->send();

        $apiData->message = "打赏成功！";
        $apiData->code    = "200";
        return $apiData->send();
    }

    //验证用户提交的数据
    public function checkUserInput($params)
    {
        $validate = \Validator::make($params,
            [
                'CommID'          => 'required',//读书改进计划的内容的ID
                'Type'            => 'required',//类型默认为0即可
                'ReaParID'        => 'required',//读书会的ID【对应的是read_party】
                'CommContents'    => 'required',//评论的内容
                'mobile'          => 'required',//用户的手机号
//                'key'             => 'required',//设备的KEY对应memberinfo表里面的字段是appkey
//                'reply_MemNumber' => '',//回复用户的唯一的编号
                'pid'             => 'required',//评论的父级ID
//                'commentTopId'    => 'required',//是否是顶级评论若是0则不是顶级评论，如果不是顶级评论则需要前端传递一个顶级的ID
                'reply_MemNumber' => 'required'//若是顶级评论则填写为0即可，如果是回复则需要填写用户的唯一的编号，对应的memberinfo表里面的memberinfo;
            ],
            [
                'CommID.required'          => '读书改进计划的内容ID不能为空',
                'Type.required'            => '类型不能为空',
                'ReaParID.required'        => '读书会的ID不能为空',
                'CommContents.required'    => '评论的内容不能为空啊',
                'mobile.required'          => '当前用户的手机号不能为空',
                'key.required'             => '设备的key值不能为空',
                'reply_MemNumber.required' => '评论用户的ID不能为空',
                'pid.required'             => '他的父级pid不能为空',
//                'commentTopId.required'    => '评论是否是顶级的评论',
                'reply_MemNumber.required' => '回复用户的编号不能为空'
            ]
        );

        return $validate;
    }

    //优化个人信息模块---添加区域与个人学习币的情况
    public function getReadPartyMemberInfo(Request $request)
    {
        $readPartyId                 = $request->input('readPartyId');
        $userId                      = $request->input('userId');
        $apiData                     = new ApiData();
        $memberModel                 = new MemberModel();
        $userInfo                    = $memberModel->get_member_info_by_id($userId);
        if (!$userInfo) {
            $apiData->message = "用户不存在";
            $apiData->code    = "2002";
            return $apiData->send();
        }


        $userInfo->MemEndTime        = Carbon::parse($userInfo->MemEndTime)->toDateString();
        $userInfo->personal_end_time = Carbon::parse($userInfo->personal_end_time)->toDateString();
        $userInfo->ReleaseDate       = Carbon::parse($userInfo->ReleaseDate)->toDateString();
        $userInfo->AddDate           = Carbon::parse($userInfo->AddDate)->toDateString();

        unset($userInfo->LoginKey);
        unset($userInfo->AppKey);
        $memNumber  = $userInfo->MemNumber;
        $studyMoney = DB::table('membermoney')->where(['MemNumber' => $memNumber, 'ReaParID' => $readPartyId])->first(['StudyMoney']);
        $studyMoney = $studyMoney ? $studyMoney->StudyMoney : 0;

        $readPartyModel = new ReadPartyModel();

        $bookModel = new BookModel();

        $readPartyMemberDetail = $readPartyModel->get_read_party_member_detail($userInfo->UserID, $readPartyId);

        if ($readPartyMemberDetail == false) {
            $apiData->message = "用户已被移出读书会";
            $apiData->code    = "2002";
            return $apiData->send();
        }
        $companyModel  = new CompanyModel();
        $readPartyInfo = $readPartyModel->get_read_party_info($readPartyId);
        $companyId     = $readPartyInfo->company_id;
        if ($companyId) {//如果是公司
            //获取公司的成员的信息根据公司的company_id与user_id获取公司成员的详细信息
            $memberCompanyInfo = $companyModel->get_company_many_member_info_by_companyId_and_userId($companyId, $userId);
//            dd($userId);
            $job                 = $memberCompanyInfo->toArray() ? $memberCompanyInfo[0]->job : null;
            $userInfo->job       = $job;
            $readPartyMemberInfo = DB::table('read_party_member')->where(['user_id' => $userId, 'read_party_id' => $readPartyId])->first(['add_date']);

            $userInfo->addPartyDate = Carbon::parse($readPartyMemberInfo->add_date)->toDateString();

            $isDrp = $this->isDrp($userId, $companyId);

            $isAdmin = $this->hasAdmin($readPartyId, $userInfo->MemNumber);

            if ($isAdmin) {
                $userInfo->isAdmin = 1;//是管理员
            } elseif ($isDrp) {
                $userInfo->isAdmin = 2;//学习官
            } else {
                $userInfo->isAdmin = 0;//普通人
            }
            //2.判断用户是否是主管返回的部门主管的user_id
            foreach ($memberCompanyInfo as $k => $v) {
                $ismangerUser = $this->hasDepartmentAdmin($v->department_id);
                $v->isManager = ($ismangerUser == $userId) ? 3 : 0;//3为是部门的主管，0表示不是部门的主管
            }
            $userInfo->comDepart = $memberCompanyInfo;

        } else {//如果是个人
            $readPartyMemberInfo    = DB::table('read_party_member')->where(['user_id' => $userId, 'read_party_id' => $readPartyId])->first(['add_date']);
            $userInfo->addPartyDate = Carbon::parse($readPartyMemberInfo->add_date)->toDateString();
            $userInfo->isAdmin      = $this->hasAdmin($readPartyId, $userInfo->MemNumber);
            $userInfo->comDepart    = [];
        }

//        if ($departmentId > 0) {//如果是公司的
//            $userInfo->department_name = $memberCompanyInfo->department_name;
//            $userInfo->department_id   = $departmentId;
//        } else {
//            $userInfo->department_name = "未分组";
//            $userInfo->department_id   = 0;
//        }
        //1.判断当前用户是否管理员和是否是学习官
        //判断用户的来源
        $city                       = $readPartyModel->getUserCity($userInfo->UserID);//获取用户所在的城市
        $readedBook                 = $bookModel->get_user_readed_book($userInfo->MemNumber);
        $userInfo->isEmployee       = $readPartyMemberDetail->is_delete === 1 ? 0 : 1;
        $userInfo->rewardRight      = $readPartyMemberDetail->reward_right;
        $userInfo->readedBookNumber = count($readedBook);
        $userInfo->city             = $city;
        $userInfo->studyMoney       = $studyMoney;
        $apiData->message           = "ok";
        $apiData->code              = "200";
        $apiData->set_data('memberInfo', $userInfo);

        return $apiData->send();
    }

    /**
     * @param $sumUpID 读书改进计划的ID
     * @param $userInfo 用户的详细的详细
     * @param $msg 推送的事件类型 评论 打赏 点赞
     * @param $title 推送的标题
     */
    public function JpushSend($sumUpID, $userInfo, $msg, $title)
    {
        //极光推送
        $bookModel    = new BookModel();//获取书籍的信息
        $commentId    = $sumUpID;
        $readPlanOwer = $bookModel->get_comment_info($commentId);//获取摸一个读书改进计划的ID


        //添加消息
        $messageCtrl = new MessageModel();
        $msg         = '' . $title . ':您的好友' . $userInfo->YourName . "" . $msg . "《" . $readPlanOwer->BookTitle . "》读书改进计划日志";
        $msgId       = $messageCtrl->add_note_message("" . $title . "", $msg);
        $messageCtrl->add_user_message($msgId, $readPlanOwer->UserID);

        //发送消息
        $push        = new Jpush();
        $push->alias = $readPlanOwer->UserName;
        $push->set_message($msg);
        $push->send();
    }

    /**
     * 转让读书会的通知
     * @param $readPartName 读书会的名字
     * @param $pushUserIdenfiy 被推送人的身份认证
     * @param $assignmentName 转让的人
     * @param $isAdminUser 成为管理员的人
     */
    public function JpushSendForAssignmentAdmin($readPartName, $pushUserIdenfiy, $assignmentName, $isAdminUser)
    {
        $push        = new Jpush();
        $push->alias = $pushUserIdenfiy;
        $msg         = $assignmentName . '把' . $readPartName . '读书会管理权限转让给你';
        $push->set_message($msg);
        $push->send();
    }

    /**
     * 读书改进计划分页的接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function readPlanListPaginate(Request $request)
    {
        $apiData      = new ApiData();
        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $parid        = $request->input('readPartid');//读书会的ID
        $bookId       = $request->input('bookId');//书籍的ID
        $page         = $request->input('page');//分页的ID
        $departmentId = $request->input('departmentId', -1);
        $firstReadPlanId=$request->input('firstReadPlanId',0);

        $params       = [
            'mobile' => [$mobile, '缺少手机号', '2037'],
            'key'    => [$key, "缺少设备ID", '2038'],
            'bookId' => [$bookId, '缺少书籍ID', '6001'],
            'parid'  => [$parid, "缺少读书会ID", '6005'],
            'page'   => [$page, "缺少页数", '6002']
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        //1.根据读书的ID 判断是否用户进入的是企业还是个人
        $readPartyModel = new ReadPartyModel();
        $bookType = DB::table('read_party')->where('ReaParID', $parid)->pluck('ReaParType')->toArray();

        $bookModel      = new BookModel();
        $bookSumup      = $bookModel->get_read_plan_by_book_readparty($bookId, $parid, $departmentId,$bookType[0],$firstReadPlanId);

        foreach ($bookSumup as $data) {
            $commentId = $data->SumUpID;
            //2.根据$bookType的类型进行判断是企业还是个人如果是企业
            if ($bookType[0] == 1) {//企业类型
                $data->zan = $readPartyModel->get_read_plan_money_gift($commentId, $parid);     //取出打赏记录
            } else if ($bookType[0] == 2) {//个人类型
                $data->isLike = preg_match("/$mobile/", $data->is_like_users) ? 1 : 0;
                //1.获取所有点赞的用户
                $isLikeUsers = $data->is_like_users;
                $isLikeUsers = explode(',', $isLikeUsers);
                unset($isLikeUsers[0]);
                foreach ($isLikeUsers as $k => $v) {
                    $userData    = DB::table('memberinfo')
                        ->where('UserName', $v)
                        ->where('DeleteMark',1)
                        ->first(['YourName', 'UserID']);
                    $data->zan[] = $userData;
                }
            }
            $data->ReleaseDate = $data->AddDate;
            $data->commentlist = $this->getAllComments($commentId, $parid); //评论 readId 读书会的ID commenId读书改进计划的ID
        }
        $apiData->message = "ok";
        $apiData->code    = "200";
        $apiData->set_data('readPlanList', $bookSumup);
        return $apiData->send_old();
    }

    /**
     * 删除部门成员
     * @param Request $request
     * @return mixed
     */
    public function delMemberUser(Request $request)
    {
        //$departmentId = $request->departmentId;//获取部门的ID
        $readPartId = $request->readPartId;//读书会的ID
        $memNumber  = $request->memNumber;//当前用户的唯一的编号 正在进行删除用户的编号
        $userId     = $request->userId;//获取用户的Id----要删除的用户的ID
        $mobile     = $request->mobile;
        $key        = $request->key;
        //1.管理员与学习官可以删除成员，且管理员与学习官不能这个成员不能删除，其中管理员可以的权限可以转让给其他人
        $hasAdmin  = $this->hasAdmin($readPartId, $memNumber);//是否是管理员
        $companyId = $this->getCompanyIdByReadPartId($readPartId);
        $hasDrp    = $this->hasDrp($mobile, $key, $companyId);//是否是学习官
        //判断当前要删除的人的身份 如果是学习官或者是管理员则不允许删除
        $isDrp   = $this->isDrp($userId, $companyId);//要删除的用户是否是学习官
        $isAdmin = $this->hasAdmin($readPartId, $this->getMemNumberByUserId($userId));
        $memberModel    = new MemberModel();

        if ($isDrp || $isAdmin) {
            return $this->response->array(['code' => '200', 'message' => '不能删除管理员或者学习官']);
        }
        if ($hasAdmin || $hasDrp) {//判断用户是否有权限进行删除操作
            //1.移除读书会
            $readPartyModel = new ReadPartyModel();
            $readPartyInfo  = $readPartyModel->get_read_party_info($readPartId);
            $companyId      = $readPartyInfo->company_id;
            $readPartyModel->remove_party_member($readPartId, $userId);
            //检查是否还存在本公司的其他读书会 如果不存在 则移出本公司
            $count = DB::table('read_party_member as a')
                ->leftJoin('read_party as b', 'b.ReaParID', '=', 'a.read_party_id')
                ->where('b.company_id', $companyId)
                ->where('a.read_party_id', '<>', $readPartId)
                ->count();
            if ($count == 0) {
                //3.公司用户信息is_delete设置为1
                $companyModel = new CompanyModel();
                $companyModel->delete_company_member($companyId, $userId);
                $memberModel->change_member_endtime($userId);

                return $this->response->array(['code' => '200', 'message' => '删除成功', 'data' => []]);
            }
            return $this->response->array(['code' => '200', 'message' => '删除成功', 'data' => []]);
        }
        return $this->response->array(['code' => '403', 'message' => '你没有权限这么操作', 'data' => []]);
    }

    /**
     * 转让公司的管理员身份
     * @param Request $request
     * @param ReadPartyModel $readPartyModel
     * @return mixed
     */
    public function assignmentAdmin(Request $request)
    {
        $readPartyModel = new ReadPartyModel();
        $userId         = $request->userId;//要成为管里员的当前用户的UserId
        $readPartId     = $request->readPartId;//读书会的ID
        $memNumber      = $request->memNumber;//

        //1.判断当前操作的用户是否是管理员
        $isAdmin = $this->hasAdmin($readPartId, $memNumber);
        //2.判断要转让的用户是否已经是管理员了
        $hasAdmin = $this->hasAdmin($readPartId, $this->getMemNumberByUserId($userId));
        if ($hasAdmin) {
            return $this->response->array(['code' => '400', 'message' => '您已经是管理员了', 'data' => []]);
        } else if ($isAdmin) {//如果是管理员
            //判断要成为管理员是否是学习官
            $companyId = $this->getCompanyIdByReadPartId($readPartId);
            $youIsDrp  = $this->isDrp($userId, $companyId);
            if ($youIsDrp) {
                return $this->response->array(['code' => '400', 'message' => '你不能转让给学习官', 'data' => []]);
            }

            $status = $readPartyModel->assignmentAdminModel($readPartId, $this->getMemNumberByUserId($userId));
            //1.获取部门的名称
            $readPartyName = DB::table('read_party')->select('ReaParName')->where('ReaParID', $readPartId)->first();
            $readPartyName = $readPartyName ? $readPartyName->ReaParName : null;
            //2.获取新管理员的名字
            $newAdmin         = DB::table('memberinfo')->select('YourName', 'UserName')->where('UserID', $userId)->first();
            $newAdminName     = $newAdmin ? $newAdmin->YourName : null;
            $newAdminIdentity = $newAdmin ? $newAdmin->UserName : null;
            //3.获取执行者的名字
            $oldAdmin     = DB::table('memberinfo')->select('YourName')->where('MemNumber', $memNumber)->first();
            $oldAdminName = $oldAdmin ? $oldAdmin->YourName : null;
            Log::info($isAdmin);
            //极光推送---管理员权限转让通知
            $msg = $oldAdminName . '把' . $readPartyName . '读书会管理权限转让给你';
            //1.判断转让管理员后读书会的通知---判断读书会的类型
            $readPartyInfo = DB::table('read_party')->where('ReaParID', $readPartId)->select('ReaParType')->first();
            $readParType   = $readPartyInfo->ReaParType;//获取读书会的类型
            $data          = ['ReadParId' => $readPartId, 'type' => $readParType];

            $data = [
                'code'    => 203,//表示进行权限转让通知
                'message' => json_encode($data)
            ];
            $this->JpushContent($msg, $newAdminIdentity, '管理员权限转让通知', $data);
//          $this->JpushSendForAssignmentAdmin($readPartyName, $newAdminIdentity, $oldAdminName, $newAdminName);
            $message = $status ? '转让成功' : '转让失败';
            return $this->response->array(['code' => '200', 'message' => $message, 'data' => []]);
        }
    }

    /**
     * 读书会列表页
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function readPartIndex(Request $request)
    {
        $readPartyModel = new ReadPartyModel();
        $apiData        = new ApiData();
        //1.头部广告
        $hotAds = $readPartyModel->get_read_party_ad();
        $apiData->set_data('hotslist', $hotAds);

        //2.会员的读书会
        $mobile      = $request->input('mobile');
        $appKey      = $request->input('key');
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $appKey);
        $readPartys  = [];

        if ($memberInfo == false) {

            $apiData->code    = '3009';
            $apiData->message = '重新登录！';
            $apiData->set_data('homegrouplist', $readPartys);
            return $apiData->send_old();
        }
        $readPartys = $readPartyModel->get_member_read_party_and_notice($memberInfo->UserID);
        foreach ($readPartys as $par) {
            $par->Description = "";
            $readPartyId      = $par->ReaParID;
            //1.获取这个读书会的所有的未读的通知
            $noticeId      = DB::table('notice_user')
                ->select('id')
                ->where(['read_party_id' => $readPartyId, 'notice_user_id' => $memberInfo->UserID, 'deleted_at' => null])
                ->get();
            $par->noticeId = $noticeId;
            //获取该读书会的成员数量
            $memberCount = $readPartyModel->count_read_party_number($readPartyId);
            $par->msun   = $memberCount;

            //查询该读书会的今日动态 实际上就是有多少人写了读书日志
            $countReadPlan = $readPartyModel->count_read_party_member_read_plan($readPartyId);
            $par->usum     = $countReadPlan;


            $states     = ['审核中', '审核通过', '审核失败'];    //0：审核中 1:审核通过 2:审核失败
            $par->sname = $states[$par->States];


            $tnames     = ['', '企业', '个人', '官方'];          //1,企业，2，个人，3，官方
            $par->tname = $tnames[$par->ReaParType];

            $par->isadmin = $par->MemNumber == $memberInfo->MemNumber ? "1" : "0";
        }

        $apiData->code    = '200';
        $apiData->message = '0k';
        $apiData->set_data('homegrouplist', $readPartys);
        return $apiData->send_old();

    }

    /**
     * 标记用户的通知为已读
     * noticeId 通知用户的唯一的ID
     * @param Request $request
     */
    public function remarkNotice(Request $request)
    {
        $mobile      = $request->mobile;
        $key         = $request->key;
        $noticeByIds = $request->noticeIds;
        $noticeByIds = explode(',', $noticeByIds);//通知的ID
        //更新用户的所有的通知为已读
        foreach ($noticeByIds as $k => $v) {
            $status = NoticeUser::where('id', $v)->update(['deleted_at' => Carbon::now()]);
        }
        if ($status) {
            return $this->response->array(['code' => '200', 'message' => '通知标记为已读成功', 'data' => []]);
        } else {
            return $this->response->array(['code' => '400', 'message' => '通知标记为已读失败', 'data' => []]);
        }
    }

    /*================== 排行榜 =============*/

    /**
     * 详细的学习信息
     * */
    public function detail_study_info(Request $request)
    {

        $memberModel    = new MemberModel();
        $readModel      = new ReadPartyModel();
        $bookModel      = new BookModel();


        $userId         = $request->input('userId',0);
        $readPartyId    = $request->input('readPartyId');

        $memberInfo     = $memberModel->get_member_info_by_id($userId);

        if($userId <= 0)
        {
            return apiData()->send(4001,"用户ID为必须大于0的整数");
        }

        if($readPartyId <= 0)
        {
            return apiData()->send(4002,"读书会ID必须大于0的整数");
        }

        //1.用户排名
        $integralRank   = $this->get_integral_rank($userId,$readPartyId);


        //2.用户已读的书籍
        $readedBookNum  = $bookModel->count_user_readed_book($memberInfo->MemNumber);


        //3.用户使用APP的时间
        $appTime            = $this->get_online_time($userId);
        $useAppTime         = (string) round($appTime / (60 * 60),1);

        //4.用户的学习币
        $studyMoney     = $readModel->get_member_money($memberInfo->MemNumber,$readPartyId);
        $memberList     = $this->get_integral_rank_list($request);

        $integralRule   = "教导读书会社群积分规则
教导读书会明师榜积分说明：
一、积分统称为自学习力：
1、明师榜是了帮助社群用户在教导读书会APP上提升学习成果，做综合学习效果展示排名；
2、用户在使用教导读书会APP过程中，根据各种学习行为获得相应自学习力积分奖励来参与社群明师榜排名。

二、自学习力如何获得：
用户在使用教导读书会APP过程中，通过【老侯论道打开签到】【代读】【自学习读书改进计划】【读书改进计划评论】来获取相应的自学习力。

规则如下：
每日听老侯论道签到——+3（每日只记录一次）；
每日听老侯论道分享一次——+5（不记次数）
言图分享一次——+5（不记次数）
自学习社群文章转发一次——+5（不记次数）
自己的读书改进计划转发一次——+5（不记次数）
听代读音频1分钟——+1，以此类推；
看代读视频1分钟——+1，以此类推；
学习完一本代读书籍并填写读书改进计划——+10；
每周三按时学习并填写读书改进计划24点前完成——+10；
评论社群成员读书改进计划1次——+2分，不限次数（回复同样计入）；
所有规则中的代读内容可反复学习，时间也可以累计。";

        return apiData()
            ->set_data('integralRank',$integralRank)
            ->set_data('readedBookNum',$readedBookNum)
            ->set_data('useAppTime',$useAppTime)
            ->set_data('studyMoney',$studyMoney)
            ->set_data('integralRule',$integralRule)
            ->set_data('members',$memberList)
            ->send(200,'ok');
    }


    /**
     * 获得某个毒素会成员的积分排名列表
     * */
    public function get_integral_rank_list(Request $request)
    {
        $readPartyId    = $request->input('readPartyId');
        $userId         = $request->input('userId');
        $timeType       = $request->input('timeType','week');


        if($timeType == 'month') //按月计算
        {
            $giftType           = "monthFlower";
            $beginTime          = date('Y-m-01 00:00:00',time()).""; //本月开始的时间
            $prevLoopBeginTime  = date('Y-m-01 00:00:00',strtotime(date('Y-m-d 00:00:00') ." - 1 month"));   //上一个月的开始时间
            $prevloopEndTime    = date('Y-m-d 59:59:59',strtotime(date('Y-m-01 00:00:00'))-1);//上一个月的

        }
        elseif($timeType == "week") //按周计算
        {
            $giftType   = "weekFlower";
            $beginTime  = prev_week_day_time(3);
            $beginTime  = date('Y-m-d 00:00:00',$beginTime);

            $prevLoopBeginTime  = date('Y-m-d 00:00:00',strtotime($beginTime ." - 7 day"));//上一周起始时间
            $prevloopEndTime    = date('Y-m-d 59:59:59',strtotime($beginTime)-1);//上一周结束时间
        }

        $members = DB::table('read_party_member as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->leftJoin('member_integral as d','d.user_id','=',DB::raw("a.user_id AND d.created_at > '{$beginTime}' "))
            ->select(DB::raw("IFNULL(SUM(d.integral),0) as integral,b.YourName,b.UserID,b.FilePath1"))
            ->where('a.read_party_id',$readPartyId)
            ->where('a.is_delete',0)
            ->where('b.DeleteMark',1)
            ->groupBy('a.user_id')
            ->orderBy('integral','desc')
            ->orderBy('b.UserID')
            ->paginate(10);

        $currentMonthBeginTime  = date('Y-m-01 00:00:01',time());
        $currentMonthEndTime    = date_time();

        //花有三张 周度花  月度花 代读花
        foreach($members as $member)
        {
            $member->FilePath1  = change_member_head_img($member->FilePath1);
            $gifts              = $this->get_member_gifts($member->UserID,$giftType,$beginTime,$readPartyId);    //获取花朵数量
            $isSendedGift       = 0;
            foreach($gifts as $gift)
            {
                if($gift->sender == $userId)
                {
                    $isSendedGift   = 1;
                    break;
                }
            }

            $member->isSendedGift   = $isSendedGift;
            $member->giftNum      = count($gifts);


            //获取上月、上周排名
            $member->prevRank   = $this->get_read_party_member_integral_rank($member->UserID,$readPartyId,$prevLoopBeginTime,$prevloopEndTime);
            $member->rankUp     = 5;

            //本月排名升级
            if($timeType == 'month')
            {
                $rank               = $this->get_read_party_member_integral_rank($member->UserID,$readPartyId,$currentMonthBeginTime,$currentMonthEndTime);
                $member->rankUp     = $member->prevRank - $rank ;
            }
        }
        return $members;
    }


    /**
     * 积分排名分页
     * */
    public function page_integral_rank_list(Request $request)
    {
        $members    = $this->get_integral_rank_list($request);
        $userId     = $request->input('userId',0);
        $readPartyId= $request->input('readPartyId');

        if($userId <= 0)
        {
            return apiData()->send(4001,"用户ID为必须大于0的整数");
        }
        if($readPartyId <= 0)
        {
            return apiData()->send(4002,"读书会ID必须大于0的整数");
        }
        return apiData()
            ->set_data('members',$members)
            ->send(200,'0k');
    }


    /**
     * 获取代读排名
     * */
    public function page_read_rank_list(Request $request)
    {
        $readPartyId    = $request->input('readPartyId');
        $userId         = $request->input('userId');

        $bookModel      = new BookModel();
        $bookInfo       = $bookModel->get_last_book_info(); //获取本期书籍
        $bookId         = $bookInfo->BookID;

        $beginTime  = prev_week_day_time(3);
        $beginTime  = date('Y-m-d 00:00:00',$beginTime);

        $members    = DB::table('read_party_member as a')
                    ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
                    ->leftJoin('booksumup as d','d.MemNumber','=',DB::raw("b.MemNumber AND d.BooKID = ".$bookId))
                    ->select(DB::raw("b.YourName,b.UserID,IFNULL(LEFT(d.AddDate,16),'') AddDate,b.FilePath1"))
                    ->where('a.is_delete',0)
                    ->where('a.read_party_id',$readPartyId)
                    ->where('b.DeleteMark',1)
                    ->groupBy('a.user_id')
                    ->orderBy('d.AddDate')
                    ->orderBy('b.UserID')
                    ->paginate(1000);

        //花有三张 周度花  月度花 代读花
        $giftType   = "readFlower-".$bookInfo->BookID;
        $haveTime   = [];
        $noTime     = [];

        foreach($members as $member)
        {
            $member->AddDate ? array_push($haveTime,$member) : array_push($noTime,$member);
        }

        $allMember  = array_merge($haveTime,$noTime);
        $i          = 0;
        foreach($members as $key => $m) //获取花朵数量
        {
            $member = $allMember[$i];$i++;
            if($member->AddDate == "3000-01-01")
            {
                $member->AddDate    = str_replace("-","/",$member->AddDate);
            }
            $member->FilePath1  = change_member_head_img($member->FilePath1);
            $gifts              = $this->get_member_gifts($member->UserID,$giftType,$beginTime,$readPartyId);

            $isSendedGift       = 0;
            foreach($gifts  as $gift)
            {
                if($gift->sender == $userId)
                {
                    $isSendedGift = 1;
                    break;
                }
            }
            $member->giftNum      = count($gifts);
            $member->isSendedGift   = $isSendedGift;
            $members[$key] = $member;
        }
        return apiData()
            ->set_data('members',$members)
            ->send(200,"ok");
    }



    //统计花朵数量
    public function count_gift($userId,$giftType,$beginTime)
    {
        $total = DB::table('member_gift')
            ->where('gainner',$userId)
            ->where('gift_type',$giftType)
            ->where('created_at','>',$beginTime)
            ->count();
        return $total;
    }

    /**
     * 获得用户获得的礼物
     * @param int $userId 用户ID
     * @param string $giftType 礼物类型
     * @param string $beginTime 开始时间
     * @param int    $readPartyId 读书会ID
     * */
    public function get_member_gifts($userId,$giftType,$beginTime,$readPartyId)
    {
        $gifts = DB::table('member_gift')
            ->where('gainner',$userId)
            ->where('gift_type',$giftType)
            ->where('created_at','>',$beginTime)
            ->where(function($db) use($readPartyId) {
                $db->where('read_party_id',$readPartyId)->orWhere('read_party_id',0);
            })->get();
        return $gifts;
    }

    /**
     * 获得用户在线时间
     * */
    public function get_online_time($userId)
    {
        $timeLength = DB::table('member_online_log')
            ->where('user_id',$userId)
            ->sum('time_length');
        return $timeLength;
    }


    /**
     * 获得用户的积分排名  本排名是给予读书会系统所有用户的排名，而不是仅仅某个读书会
     * @param integer $userId       用户ID
     * @param integer $readPartyId  读书会ID
     * */
    public function get_integral_rank($userId,$readPartyId)
    {
        //1.获得用户的积分
        $integral = DB::table('member_integral')->where('user_id',$userId)->sum('integral');
        $sql = "SELECT COUNT(*) AS total
                FROM
                (SELECT
                    sum(integral) AS totalIntegral
                    FROM  read_party_member as a
                    LEFT JOIN member_integral as b ON  b.user_id = a.user_id
                    WHERE a.user_id <> $userId
                    AND   a.read_party_id = $readPartyId
                    AND   a.is_delete = 0
                    GROUP BY a.user_id
                    HAVING (totalIntegral > $integral)
                ) AS d";
        $info= DB::select($sql);
        return $info[0]->total+1;
    }

    /**
     * 获取读书会成员排名
     * @param int $userId 用户ID
     * @param int $readPartyId 读书会ID
     * @param string $beginTime 起始时间
     * @param string $endTime   结束时间
     * */
    public function get_read_party_member_integral_rank($userId,$readPartyId,$beginTime,$endTime)
    {
        $integral = DB::table('member_integral')
            ->where('user_id',$userId)
            ->where('created_at',">",$beginTime)
            ->where('created_at',"<",$endTime)
            ->sum('integral');

        $sql = "SELECT COUNT(*) AS total
                FROM
                (
                SELECT sum(m2.integral) AS totalIntegral
                FROM  read_party_member m1
                LEFT JOIN member_integral m2 ON m2.user_id = m1.user_id
                WHERE m1.user_id <> {$userId}
                AND   m1.read_party_id = $readPartyId
                AND   m2.created_at > '{$beginTime}'
                AND   m2.created_at < '{$endTime}'
                GROUP BY m1.user_id
                HAVING (totalIntegral > $integral)) AS a";
        $info= DB::select($sql);

        return $info[0]->total+1;
    }


    /**
     * 赠送礼物
     * */
    public function send_gift(Request $request)
    {
        $sender     = $request->input('sender');    //礼物赠送者
        $gainner    = $request->input('gainner');   //礼物获得者
        $giftType   = $request->input('giftType');
        $readPartyId= $request->input('readPartyId',0);

        if($giftType == 'readFlower')
        {
            $bookModel  = new BookModel();
            $bookInfo   = $bookModel->get_last_book_info();
            $bookId     = $bookInfo->BookID;
            $giftType   = $giftType."-".$bookId;
        }
        $date   = date_time();
        $data   = [
            'sender'    => $sender,
            'gainner'   => $gainner,
            'gift_type' => $giftType,
            'created_at'=> $date,
            'updated_at'=> $date,
            'read_party_id' => $readPartyId
        ];
        DB::table('member_gift')->insert($data);
        return apiData()->send(200,'ok');
    }


    /**
     * 总的排行榜
     * */
    public function all_integral_rank(Request $request)
    {
        $readPartyId  =   $request->input('readPartyId',0);
        if($readPartyId > 0)
        {
            $members = DB::table('read_party_member as a')
                ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
                ->leftJoin('member_integral as d','d.user_id','=','a.user_id')
                ->select('b.FilePath1',DB::raw("IFNULL(sum(d.integral),0) as integral,IFNULL(b.YourName,'') as YourName"))
                ->where('a.is_delete',0)
                ->where('b.DeleteMark',1)
                ->where('a.read_party_id',$readPartyId)
                ->groupBy('a.user_id')
                ->orderBy('integral','desc')
                ->paginate(20);
        }else{

            $members = DB::table('member_integral as a')
                ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
                ->select("b.FilePath1",DB::raw("sum(a.integral) as integral,IFNULL(b.YourName,'') as YourName"))
                ->groupBy('a.user_id')
                ->orderBy('integral','desc')
                ->paginate(20);
        }

        foreach($members as $member)
        {
            $member->FilePath1  = change_member_head_img($member->FilePath1);
        }
        return apiData()->set_data('data',$members)->send_old(200,"ok");
    }

}
